[英]Get a set of related records from multiple related records laravel?
我有多個restaurants
users
,然后每個restaurant
都有comments
。
因此,當user
登錄時,我想顯示restaurants
與該用戶相關的所有comments
的列表。
我正在使用laravel 5.1
到目前為止,我有:
$restaurants = $user->restaurants;
$comments = null;
foreach ($restaurants as $restaurant) {
if (!$comments){
$comments = $restaurants->comments();
} else{
$comments = $comments->merge($restaurant->comments());
}
}
$rows = $comments->paginate(15);
$count = $comments->count();
我收到BadMethodCallException
,我想我不是以laravel的方式這樣做。
您是否嘗試過許多?
在用戶模型中, public function user_posts() { return $this->hasManyThrough('App\\Comment', 'App\\Restaurant'); }
public function user_posts() { return $this->hasManyThrough('App\\Comment', 'App\\Restaurant'); }
並且在控制器ü容易訪問評論 $comments = $user->user_posts();
此處有更多詳細信息: https : //laravel.com/docs/5.1/eloquent-relationships#has-many-through
我剛剛找到了答案,要使用merge
,數據集需要是一個collection
。
因此,創建集合需要使用: ->get();
在我的示例中:
$comments = $restaurants->comments()->get();
注意:必須啟用分頁功能,這不是laravel Collection
方法
你幾乎是正確的,你應該做的
$restaurant->comments
// gives you objects
代替
$restaurant->comments()
// gives you query builder
// $restaurants->comments()->get() would also work as someone mentioned
至於分頁,你可以做
$restaurants->comments()->paginate(15)
代替
$restaurants->comments()->get()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.