![](/img/trans.png)
[英]How to retrieve records from a table based on many to many relationship using eloquent in Laravel?
[英]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.