当使用多对多关系Laravel / Eloquent / Query构建器时,如何从另一个表中获取所有书籍

问题描述:

Let me explain the scenario.

i have tables:

competitions

id title body

then

books

id name user_id

then i have a pivot table to store participants

so

participants

id competition_id user_id

Now i have set some relationships for these models.

Competition model

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

User model

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

Now i am fetching one single competition and in that same query i need to fetch a list of books of the participants of that competition. So how can i achieve this. Thanks.

Here is how you get all the books:

$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();