【问题标题】:Laravel whereHas Returns all recordsLaravel whereHas 返回所有记录
【发布时间】:2021-12-04 21:48:08
【问题描述】:

我的项目中有 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);



【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    如果你有一个产品的 n 个变体,你的查询应该是这样的:

    产品型号

    公共函数变体:HasMany 关系

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

    【讨论】:

    • 嗨,谢谢你的回复,我的关系就像你说的,但我想按产品过滤变体->attributeValues 有你的想法吗?
    • 您可以使用查询函数来调查最终查询结果以了解该查询的哪些部分存在问题,如果您在查询中找不到问题,请更新 aswer 并放置在这里给大家看
    【解决方案2】:

    你需要以这种方式使用它,它应该可以工作:

    $productId = $request->product_id;
    
    $valueIds = $request->value_ids;
    
    $searchedVariants = Variant::whereHas('product.attributeValues', function ($query) use ($valueIds) {
        $query->distinct()->whereIn('value_id', $valueIds);
    }, '=', count($valueIds))->where('product_id', $productId)->get();
    

    【讨论】:

    • 我使用了与您发送的完全相同的查询,但现在查询返回空记录,我确信搜索结果存在变体
    猜你喜欢
    • 2021-06-10
    • 2019-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 2021-12-20
    • 2014-10-16
    • 1970-01-01
    • 2019-05-26
    相关资源
    最近更新 更多