I have a situation where I need data within data while doing a DB call.
For example I have a post, that has many comments, but then there is a user to that comment in another table.
So I have
$post = Posts::where('id', $id)->with('comments')->first();
and Posts model is
public function comments()
{
return $this->hasMany('App\Models\Comments', 'postId', 'postId');
}
This works well, I get the post and all the comments but now I need to get the users for those comments. How would I include that?
CodePudding user response:
This would be
$post = Posts::where('id', $id)->with('comments', 'comments.user')->first();
or what ever you have called the user relation on the comment. or
class Comment extends Model
{
protected $with = ['user'];
public function user()
{
return $this->belongsTo(User::class);
}
}
Will always return the user with the comment.