[英]Laravel eloquent relation query multiple
我有一个带有关系表和数据透视表的模型。
图书
身份证名称
1 本书 1
2 书 2
3 书 3
类型
身份证名称
1 小说
2 非虚构
3 杂志
4 精装本
5 期刊
6 喜剧
类型预订
book_id type_id
1 2
1 3
2 2
2 4
正如您所看到的,一本书可以有多种类型,现在我想要做的是根据用户输入搜索一本书可能具有的所有类型的查询。 例如,如果用户搜索非小说杂志书籍,我希望返回书籍 1。
目前我的代码同时返回第 1 本书和第 2 本书 - 因为第 2 本书是一本非小说类书籍,但除非满足这两个条件,否则它不应返回。
当前代码
$search = ['nonfiction','magazine'];
$books = Book::whereHas('types', $filter = function($query) use ($search){$query->whereIn('name',$search);
})
->get();
模型
public function types()
{
return $this->belongsToMany('App\Type');
}
我可以在模型中使用此函数实现我的结果,但是我无法以这种方式传递变量,我该怎么做?
return $this->belongsToMany('App\Book')->wherePivotIn('type_id', [1,2]);
在您的书籍模型中,通过 bookid 与 booktype 表建立 hasMany 关系
use App\Book;//in top of your model
public function bookWithType() {
return $this->hasMany(Book::class, 'book_id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.