简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM