Home > Software engineering >  laravel, how to select with all values
laravel, how to select with all values

Time:12-28

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

CodePudding user response:

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');
  • Related