首页 > 解决方案 > Laravel whereHas 返回所有记录

问题描述

我的项目中有 3 个表,它们是:

我想通过来自表单请求的值 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);



标签: laravellaravel-5eloquent

解决方案


如果您对一种产品有 n 个变体,则查询应如下所示:

产品型号

公共函数变体:HasMany 关系

//用法 $produtc->variants->这里是查询函数


推荐阅读