[英]Laravel one-to-many relationship query with LIKE option
I have tables like this我有这样的桌子
brands
- id
- name
- status (default=1)
products
- id
- brand_id
- name
and I want to query a " keyword " so it should match with either " brand.name " or " product.name ".我想查询一个“关键字”,所以它应该与“ brand.name ”或“ product.name ”匹配。 Here is my current query which works fine with " brand.name ", but I am not sure how to use this with " product.name ".这是我当前的查询,它适用于“ brand.name ”,但我不确定如何将它与“ product.name ”一起使用。
Brand::where('status', 1)->where('name', 'like', "%{$keyword}%")->get()->sortBy('name')
It is one-to-many relationship as one brand can have many products.这是一对多的关系,因为一个品牌可以有很多产品。
use whereHas
to search in the related models.使用whereHas
在相关模型中搜索。 assuming the hasMany
relation name is products
.假设hasMany
关系名称是products
。
Brand::where('status', 1)
->where(function ($query) use ($keyword) {
$query->where('name', 'like', "%{$keyword}%")
->orWhereHas('products', function ($query) use ($keyword) {
$query->where('name','LIKE',"%{$keyword}%");
});
})
->get();
Useful reading: Querying Relationship Existence有用的阅读: 查询关系存在
Try this query:试试这个查询:
Brand::leftJoin('products', 'brands.id', '=', 'products.brand_id')
->where('status', 1)
->whereRaw('brands.name like "%'.$keyword.'%" OR products.name like "%'.$keyword.'%"')
->get()->sortBy('name');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.