how to filter records filtered by more than one cr

2019-05-21 18:10发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-05-21 18:58

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();
查看更多
登录 后发表回答