How to select rows having same column condition in Laravel Eloquent method or SQL

Viewed 111

I have a table 'product_attribute_option' having columns

product_id    attribute_id    attribute_option_id
 1             9                    15
 1             15                   23
 2             9                    15
 2             11                   18
 2             12                   19
 3             9                    15
 3             15                   23

now I want to filter product by attribute_option.

How to get distinct product_ids having attribute_option_id 15 and 23?

3 Answers

You can use aggregation and a having clause:

select product_id
from t
where attribute_option_id in (15, 23)
group by product_id
having count(distinct attribute_option_id) = 2;

 

Use the below code:

$products = Products::select('product_id')
    ->whereIn(attribute_option_id, [15, 23])
    ->distinct('attribute_option_id')
    ->groupBy('product_id')
    ->get();
    

make sure the name of relations [attribute,option] is correct

attributes is product has many attributes, option is attribute has one or many options

`$products = Products::query()
    ->whereHas('attributes',function($q){
        $q->whereHas('option',function($q){
          $q->whereIn('id',[15,23]))})
    ->pluck('product_id')->toArray();`
Related