简体   繁体   中英

Laravel Eloquent get specific relationship

I'm trying to get the books where the authors are from a specific country, for now my query looks like this :

$books->with('author')->where('country', '=',  'FR'); 

but the where is applied to books and not to authors

any help ?

You need to use whereHas() for that. The following code should do the trick:

$country = 'FR';
$books = Book::with('author')->whereHas('author', function($query) use ($country) {
  $query->where('country', '=',  $country);
})->get();

This will give you all books that have a related author, that has country column set to FR .

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