how to filter records filtered by more than one criterion in pivot table - laravel eloquent collections

余生颓废 提交于 2019-12-10 10:42:41

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!