Coder Perfect

How to achieve this in Laravel using a subquery


In Laravel, how do I make this query:

FROM `products` p 
WHERE `p`.`id` IN (
    FROM `product_category`
    WHERE `category_id` IN ('223', '15')
AND `p`.`active`=1

I could do this using a join, but this format is required for performance.

Asked by Marc Buurke

Solution #1

Consider this code:

Products::whereIn('id', function($query){
    ->from(with(new ProductCategory)->getTable())
    ->whereIn('category_id', ['223', '15'])
    ->where('active', 1);

Answered by lukaserat

Solution #2

Take a look at Fluent’s advanced where clause documentation. Here’s an illustration of what you’re attempting to accomplish:

    ->whereIn('id', function($query)
              ->whereRaw('orders.user_id =');

This will produce:

select * from users where id in (
    select 1 from orders where orders.user_id =

Answered by drewjoh

Solution #3

The keyword “use ($category id)” can be used to use a variable.

$category_id = array('223','15');
Products::whereIn('id', function($query) use ($category_id){
     ->from(with(new ProductCategory)->getTable())
     ->whereIn('category_id', $category_id )
     ->where('active', 1);

Answered by Ramesh

Solution #4

Eloquent can be used in a variety of queries to make them easier to understand and maintain:

$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
                   ->select('product_id'); //don't need ->get() or ->first()

Then we put everything together:

Products::whereIn('id', $productCategory)
          ->where('active', 1)
          ->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
          ->get();//runs all queries at once

The query you wrote in your inquiry will be generated as a result of this.

Answered by Philipe

Solution #5

The code below worked for me.

->whereIn('columnName',function ($query) {


Answered by Aditya Singh

Post is based on