For example, i have Post and Comment models. When i load hasMany relation, i want to get separate parent item for each relation item.
Post.php:
class Post extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Comment.php:
class Comment extends Model
{
public function comments()
{
return $this->belongsTo('App\Post');
}
}
When i load post with comments
Post::where('title', 'LIKE', search)
->orWhereHas('comments', function ($query) use ($search) {
$query->where('text', 'LIKE', $search)
})
->paginate();
results looks like this
[
{
post_id: 1,
comments: [
{
comment_id: 1
post_id: 1
},
{
comment_id: 2
post_id: 1
},
{
comment_id: 3
post_id: 1
},
]
},
...
]
but i need it to look like this (separate Post for each Comment).
[
{
post_id: 1,
comments: [
{
comment_id: 1
post_id: 1
}
]
},
{
post_id: 1,
comments: [
{
comment_id: 2
post_id: 1
}
]
},
{
post_id: 1,
comments: [
{
comment_id: 3
post_id: 1
}
]
},
...
]
Can i do it with Laravel?
My Answer:
Yes, you can achieve this by using the `with` method in your query. Here's how you can modify your query to get separate parent items for each relation item:
php
Post::where('title', 'LIKE', $search)
->orWhereHas('comments', function ($query) use ($search) {
$query->where('text', 'LIKE', $search)
})
->with(['comments' => function ($query) {
$query->select('comment_id', 'post_id');
}])
->get();
By using the `with` method and selecting only the necessary columns in the closure, you can achieve the desired result of having separate parent items for each comment.
Rate this post
3 of 5 based on 3026 votesComments