如何过滤由多个标准在数据透视表中过滤的记录 - laravel雄辩的收藏 [英] how to filter records filtered by more than one criterion in pivot table - laravel eloquent collections

查看:170
本文介绍了如何过滤由多个标准在数据透视表中过滤的记录 - laravel雄辩的收藏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在重塑一本推荐书的个人网站。我想通过一个以上的标准来过滤图书。



例如,我想显示所有这些两本哲学和科幻小说的书籍。 Peter Watt的Blindsight就是这个例子。



现在我只能做一个标准过滤器:



有一个枢轴表



模型图书

  public function genres )
{
return $ this-> belongsToMany('App \Genre','bookgenres','book_id','genre_id');
}

模特类型:

  public function books()
{
return $ this-> belongsToMany('App \Book','bookgenres','genre_id','book_id );
}

数据透视表 bookgenres 示例:
id book_id genre_id



1 - 23 - 4



2 - 23 - 5



3 - 24 - 4



简单的英文:#23是SF(#4)和哲学(#5),而#24只是SF #4)



有了这些,我只是查询

  $类型= 4; 
$ books = Genre :: find($ genre) - > books() - > get();

并使用标准的@foreach循环列出图书






要执行以下操作:过滤集合的两种类型,而不是一种。



感谢提前!

解决方案

您可以查询与 whereHas



使用类型的名称。如果你想要也可以使用id。只需更改列名称,然后更改数组。

  $ genres = array('philosophy','science-fiction'); 
$ books = Book :: whereHas('genres',function($ query)use($ genres){
$ query-> whereIn('name',$ genres);
}) - >得到();


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!

解决方案

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

这篇关于如何过滤由多个标准在数据透视表中过滤的记录 - laravel雄辩的收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆