laravel - Laravel whereHas 返回所有记录
问题描述
我的项目中有 3 个表,它们是:
- 产品(可以有多个变体)
- 变体(属于产品)
- product_attributes(这有 product_id、attribute_id、value_id)
我想通过来自表单请求的值 id 从产品中过滤变体,例如 (1,2,6)
我试过这样:
$poruduct_id = $request->product_id;
$value_ids = $request->value_ids;
$searched_variants = Variant::whereHas('product.attributeValues', function ($query) use ($value_ids, $product_id) {
$query->whereIn('value_id', [$value_ids]);
})->where('product_id', $product_id)->get();
dd($searched_variants);
但问题是查询返回产品的所有记录。准确过滤产品变体具有的值的解决方案是什么?
谢谢你。
-更新-
我试过这样但没有任何改变
$searched_variants = Variant::select('product_id')->whereHas('product.attributeValues', function ($query) use ($value_ids, $product_id) {
$query->whereIn('value_id', [$value_ids]);
})->groupBy('product_id')
->havingRaw('COUNT(*) = ?', [count((array) $value_ids)])
->get();
-**FİNALLY SOLUTİON**-
I made it like this : I get the value code that is in for example Large the code is L
get all the codes to controller and executed this query ı hope this helps someone
1.$value_codes=$request->value_codes;
2.$value_codes_array=explode(',',$value_codes);
3.$product_id=$request->product_id;
4.$searchValues = preg_split('/,/', $value_codes_array, -1, PREG_SPLIT_NO_EMPTY);
$searchValues = preg_split('/,/', $value_idss, -1, PREG_SPLIT_NO_EMPTY);
$variants= Variant::where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('sku', 'like', "%-{$value}")
->orWhere('sku', 'like', "%-{$value}-%")
->orWhere('sku', 'like', "{$value}-%");
}
})->where('product_id',$product_id)->get();
dd($variants);
解决方案
如果您对一种产品有 n 个变体,则查询应如下所示:
产品型号
公共函数变体:HasMany 关系
//用法 $produtc->variants->这里是查询函数
推荐阅读
- asp.net - “找不到类型或命名空间 HttpPostedFileBase”” - 添加 system.web 后
- javascript - 识别新窗口何时关闭
- openwrt - 如何更改 opkg 配置
- node.js - 访问或传递 Express Session 数据到 Angular 6
- javascript - 如何在输入离开包含的元素时启用/禁用 mousemove 功能(使用 mouseenter 和 mouseleave)
- c# - 如何使私有变量对选择类可见
- c# - 在 .NET Standard 中使用配置文件不起作用
- android - 通过点击三星设备上的背景不会关闭 AlertDialog
- javascript - 如何从一组可渲染组件构建 JSX 组件树?
- ios - 直接从我自己的 iOS 应用程序打开 Microsoft Office 文档以进行就地编辑