phpmysqllaraveleloquentsubquery

How to do this in Laravel, subquery where in


How can I make this query in Laravel:

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 also do this with a join, but I need this format for performance.


Solution

  • 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();