Home > OS >  Laravel whereHas Returns all records
Laravel whereHas Returns all records

Time:10-18

I have have 3 tables in my projects they are:

  • products(can have Multiple Variants)
  • variants (belongsto product)
  • product_attributes (this have product_id,attribute_id,value_id)

I want to filter variants from a product by value ids thats comes from form request as example (1,2,6)

I have tried like this:

$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);

But the problem is the query returns all records from the product. What is the solution to filter exactly the values that the product Variants have?

Thank you.

-UPDATED-

I have tried like this but nothing changed

$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();

CodePudding user response:

If you have n variants to one product, you query should be like:

Product Model

public function variants: HasMany relationships

//usage $produtc->variants->and here the query function

CodePudding user response:

You need to use it in this way, it should work:

$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();

CodePudding user response:

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

I use this but now its comes empty records

  • Related