skip to Main Content
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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search