簡體   English   中英

Laravel / Eloquent / Query builder使用多對多關系時如何從另一個表中獲取所有書籍

[英]How to get all books from another table when using many to many relationship Laravel / Eloquent / Query builder

讓我解釋一下情況。

我有桌子:

competitions

id title body

然后

books

id name user_id

然后我有一個數據透視表來存儲participants

所以

participants

id competition_id user_id

現在,我為這些模型設置了一些關系。

Competition模式

 public function participants()
    {
        return $this->belongsToMany('App\User');
    }

User模型

 public function participatedCompetitions()
    {
        return $this->belongsToMany('App\Competition');
    }

現在,我正在獲取一個競賽,在同一查詢中,我需要獲取該競賽參與者的書籍清單。 所以我怎么能做到這一點。 謝謝。

這是您獲取所有書籍的方式:

$userIds = $competition->participant()->get()->pluck('id');
// $userIds is your collection of User Ids that is participant in that compititions.
$books = Book::whereIn('user_id',$userIds)->get();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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