问题
Hello guys I am using Laravel 5.6 I have three tables in the database posts,comments and replies and three models Post , Comment , Reply
the relations are as follow one post has many comments and one comment has many replies. I created a route that when hit will return some data ;however, I want this data to be in a specific way read this example:
Lets say I have 6 posts in my database and each post has 6 comments also each comment has 6 replies I want to return only the first 3 posts along with the first 3 comments for each post also the first 3 replies for each comment
//this is a function inside a controller
//and for sure I have make sure to make use of the models namespaces
public function test(){
$posts = Post::with(['comments' => function($data){
return $data->take(3);
},
'comments.replies' => function($data){
return $data->take(3);
}])->paginate(3);
//returning the posts
return $posts
}
This way is working it returns the first 3 post and it returns the first 3 comments and first 3 replies only for the first post but for other posts I only get an empty key of comments so there is no replies as a result
hope you get my question please help sorry for big question Thanks in advance.
回答1:
There is no native support for this in Laravel.
I created a package for it: https://github.com/staudenmeir/eloquent-eager-limit
Use the HasEagerLimit
trait in both the parent and the related model.
class Post extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
class Comment extends Model {
use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}
Then you can apply ->take(3)
to your relationship.
The same goes for the replies.
来源:https://stackoverflow.com/questions/50570576/how-to-load-laravel-with-nested-models-and-limit-the-nested-models