如何在 Laravel 中执行此操作,子查询在哪里

2022-01-23 00:00:00 subquery php mysql laravel eloquent

如何在 Laravel 中进行此查询:

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.

推荐答案

考虑一下这段代码:

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

相关文章