Home > Software engineering >  Finding the exact occurrence of Laravel
Finding the exact occurrence of Laravel

Time:11-03

Products::whereIn('category_id', ['223', '15', '20'])
    ->where('active', 1)
    ->get();

How can I fix this example so that it finds the exact occurrence of category_id = 223 and 15 and 20 and also necessarily active = 1?

CodePudding user response:

It makes no sense to look for exactly category_id = 15, 20 and 223, it can only be one...

But, if you still want that, your query is nearly there, you can do:

Products::where('category_id', '223')
    ->where('category_id', '15')
    ->where('category_id', '20')
    ->where('active', 1)
    ->get();

But, again, that should return an empty Collection. whereIn is a simple IN in SQL, that means it is an OR for all the values you want.

CodePudding user response:

Use from this group. Because, maybe you use OR condition in future. Therefore, your condition will not work correctly. For example


    Products::query()->where(function ($query){
        $query->where('category_id', '223')
            ->where('category_id', '15')
            ->where('category_id', '20');
    })->where('active', 1)
    ->get();

Explain of query above will work like that:

Select * from products where (category_id = 223 and category_id = 15 and category_id = 20) and active = 1
  • Related