Sunday, January 2, 2022

[FIXED] laravel, how to select with all values

Issue

whereIn returns product_id if it has any property_option_id in $property_values. How to return if it have all from $property_values?

/*
arr int $property_values
 
db property_product_values
id, product_id, property_option_id
*/ 
    
$query->select('property_values.product_id')
                ->from('property_values')
                ->whereColumn('property_values.product_id', 'products.id')
                ->whereIn("property_values.property_option_id", $property_values);

Solution

This solution will return the product_ids having all the property values if there are no duplicate entries by product_id & property_option_id.

$query->select('property_values.product_id')
    ->from('property_values')
    ->whereIn('property_values.property_option_id', $property_values)
    ->groupBy('property_values.product_id')
    ->having(DB::raw('count(product_id)'), '>=', count($property_values))
    ->pluck('property_values.product_id');


Answered By - N69S

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.