I have three tables (users,posts and comments) and want to retrieve a certain post with creator and all related comments on it. Such Laracast
User model
public function posts()
{
// A user can have many posts
return $this->hasMany('App\Post');
}
public function comments()
{
// A user can have many comments
return $this->hasMany('App\Comment');
}
Post model:
public function user()
{
// A post is owned by a user
return $this->belongsTo('App\User');
}
public function comments()
{
// A post can have many comments
return $this->hasMany('App\Comment');
}
Comment model:
public function user()
{
// A comment is owned by a user
return $this->belongsTo('App\User');
}
public function posts()
{
// A comment is owned by a post
return $this->belongsTo('App\Post');
}
You can then use the following to get the relevant details
$post->title //or whatever you need to get from the model
$post->user->name //get the owners name
//loop over the comments
foreach($post->comments as $comment){
$comment->message //message comment
}