Skip to content

Instantly share code, notes, and snippets.

@sineld
Created September 25, 2012 13:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sineld/3781705 to your computer and use it in GitHub Desktop.
Save sineld/3781705 to your computer and use it in GitHub Desktop.
Laravel Table relationships (how to)
Based on: http://forums.laravel.com/viewtopic.php?id=2650
Question:
Hi friends,
I have just started with laravel (beautiful product) and have a question about table relationships.
I have three tables (projects / articles / images)
Image data for both projects and articles is stored in the images table e.g.
id, filename, content_id, content_type, ... (2133, asdfgh.jpg, 234, project, ...)
The images table has a one-to-many relationship with 2 tables. Therefore how do i represent the relationship in the model?
Vinay
Answer:
<?php
// models/project.php
class Project extends Eloquent {
public function images()
{
return $this->has_many('Image', 'content_id')->where_content_type('project');
}
}
// models/article.php
class Article extends Eloquent {
public function images()
{
return $this->has_many('Image', 'content_id')->where_content_type('article');
}
}
// models/image.php
class Image extends Eloquent {
public function parent_content()
{
return $this->belongs_to($this->content_type, 'content_id');
}
}
Then you can get the images as you usually except if you eager-load them you have to constrain the eager load too.
// regular
$article = Article::find($id)->first();
$images = $article->images;
// eager load
$user = Auth::user();
$articles = Article::with(array(
'images' => function($query)
{
$query->where_content_type('article');
},
))->where_user_id($user->id)->get();
// Usage
// Controller
$articles = Article::with(array('authors', 'cities'))->where('created_at', '>', $whatever)->order_by('created_at', 'desc')->paginate( 25 );
//View
@foreach( $articles as $article )
{{ $article->name }} by {{ $article->author->name }} from {{ $article->city->name }}
@endforeach
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment