如何与Take和Laravel一起使用?

时间:2019-02-04 18:10:01

标签: laravel

return $this->belongsToMany(Comment::class)
            ->orderBy("id", "desc")
            ->take(3);

Post::query()->with('comments')
             ->get;

如何解决,什么可行?

1 个答案:

答案 0 :(得分:0)

请尝试以下操作:

return $this->belongsToMany(Comment::class);

和:

Post::with([
    'comments' => 
            function(Builder $query) { 
                    $query->orderBy("id", "desc")
                          ->take(3);
            }
    ])
    ->get();

因此,您可以将with中的函数传递给filterordertake或任何其他Builder方法,以将其应用于指定的关系。

通常:

Model::with(['relationship' => function(Builder $query)
{
    // some code to filter, orderBy or take from relationship 
})->get()