问题
I am remodeling a book recommendation personal site. I want to filter books by more than one criterion.
For example, I want to display all books which are BOTH philosophy and science-fiction. Peter Watt's Blindsight being an example of this.
Now I can do only a single criterion filter:
I have a pivot table for
Model Books
public function genres()
{
return $this->belongsToMany('App\Genre', 'bookgenres', 'book_id', 'genre_id');
}
Model Genre:
public function books()
{
return $this->belongsToMany('App\Book', 'bookgenres', 'genre_id', 'book_id');
}
The pivot table bookgenres sample:
id
,book_id
, genre_id
1 - 23 - 4
2 - 23 - 5
3 - 24 - 4
In plain English: The book #23 is both SF (#4) and philosophy (#5), while book #24 is only SF (#4)
With these, I just query
$genre = 4;
$books = Genre::find($genre)->books()->get();
and use a standard @foreach loop to list books
To do: filter the collection by two genres, not one.
Thanks in advance!
回答1:
You can query relations with whereHas
Here I'm using the name of the genre. If you want you can also use the id. Just change the column name and obviously the array.
$genres = array('philosophy', 'science-fiction');
$books = Book::whereHas('genres', function($query) use ($genres){
$query->whereIn('name', $genres);
})->get();
来源:https://stackoverflow.com/questions/27665636/how-to-filter-records-filtered-by-more-than-one-criterion-in-pivot-table-larav