Coder Perfect

How to achieve this in Laravel using a subquery

Problem

In Laravel, how do I make this query:

SELECT 
    `p`.`id`,
    `p`.`name`, 
    `p`.`img`, 
    `p`.`safe_name`, 
    `p`.`sku`, 
    `p`.`productstatusid` 
FROM `products` p 
WHERE `p`.`id` IN (
    SELECT 
        `product_id` 
    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){
    $query->select('paper_type_id')
    ->from(with(new ProductCategory)->getTable())
    ->whereIn('category_id', ['223', '15'])
    ->where('active', 1);
})->get();

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:

DB::table('users')
    ->whereIn('id', function($query)
    {
        $query->select(DB::raw(1))
              ->from('orders')
              ->whereRaw('orders.user_id = users.id');
    })
    ->get();

This will produce:

select * from users where id in (
    select 1 from orders where orders.user_id = users.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){
   $query->select('paper_type_id')
     ->from(with(new ProductCategory)->getTable())
     ->whereIn('category_id', $category_id )
     ->where('active', 1);
})->get();

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.

$result=DB::table('tablename')
->whereIn('columnName',function ($query) {
                $query->select('columnName2')->from('tableName2')
                ->Where('columnCondition','=','valueRequired');

            })
->get();

Answered by Aditya Singh

Post is based on https://stackoverflow.com/questions/16815551/how-to-do-this-in-laravel-subquery-where-in