[英]Laravel Eloquent Relationship Like Query
I am trying to query categories where product tags is equal to user selected tags in filter bar, Here is the query what I have tried so far:我正在尝试查询产品标签等于过滤栏中用户选择的标签的类别,这是我迄今为止尝试过的查询:
$categories = Category::with('products');
// selected tags is array which contain tags
if (! empty($selectedTags)) {
foreach ($categories->get() as $category) {
$categories = $category->whereHas('products', function ($query) use ($selectedTags) {
foreach ($selectedTags as $tag) {
$query->where('tags','LIKE','%'.$tag.'%');
}
});
}
}
$categories = $categories->distinct()->paginate(3);
On First attempt means when I select single checkbox of tag it is working fine but not multiple selected checkboxes在第一次尝试时意味着当我 select 标记的单个复选框时它工作正常但不是多个选中的复选框
Please note that tags column in product table is comma separated values that's why I am trying to access it via like query.请注意,产品表中的标签列是逗号分隔值,这就是我尝试通过类似查询访问它的原因。
You just need to be adding to the same builder you started to build the query with instead of using a new builder every iteration of the loop:您只需要添加到您开始构建查询的同一个构建器,而不是在循环的每次迭代中使用新的构建器:
$categories = Category::with('products');
if ($selectedTags) {
$categories->whereHas('products', function ($query) use ($selectedTags) {
foreach ($selectedTags as $tag) {
$query->orWhere('tags', 'LIKE', '%'. $tag .'%');
}
});
}
$categories = $categories->distinct()->paginate(3);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.