簡體   English   中英

從多個相關記錄中獲取一組相關記錄laravel?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM