Is it possible to use eloquent to retrieve just the first match in a one to many relationship?
What do I mean, well, let me explain.
Most of us are familiar with the common one to many relationship of (or between) posts
and comments
,
as in:
Which is represented in laravel as:
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
So I wanted to find out if it is possible to retrieve post(s) with just the first comment in the result and not all comments that belong to the post(s).
$posts = Post::with('comments.0')->get();
$post = Post::with('comments.0')->first();
With comments.0
, as my way of saying, get just the first comment belonging to the each or that post.
I have looked at this question and I was wondering how it could be done using eloquent?
Thank you.
Problem:
To get 1 Comment per Post you will have to limit the subquery. I would do it like that:
Solution:
Post::with(['comments' => function ($query){
return $query->first();
}])->get();
With that, we are returing the first() comment and get() all posts do do so for.