如何使用laravel在where子句中传递select子查询

时间:2015-01-20 06:53:25

标签: laravel

这是我的SQl查询

select sum(stock.total_in_stock) as total_in_stock
    ,stock.name
    ,stock.inventory_id 
from (
    select i.store_id
        ,i.model_id
        ,i. total_in_stock
        ,i.id as inventory_id
        , m.* 
    from `inventory` as `i` 
    left join `model_store` as `ms` on `ms`.`store_id` = `i`.`store_id`
    left join `model` as `m` on `m`.`id` = `ms`.`model_id` 
    where `i`.`model_id` = m.id 
    and `m`.`status` = 1 
    and `ms`.`status` = 1 
    and `i`.`created_at` = (
        select si.created_at 
        from inventory AS si 
        where si.model_id = i.model_id 
        and si.store_id = i.store_id 
        and si.status=1 
        order by si.created_at desc limit 1
    )
) as stock 
group by stock.model_id 

在laravel中,它写成:

$results1 = DB::table('inventory as i')
                ->select(DB::raw( 'sum(stock.total_in_stock) as total_in_stock,stock.name,stock.inventory_id FROM ( SELECT i.store_id,i.model_id,i. total_in_stock,i.id as inventory_id, m.* '))                      
                ->leftJoin('model_store as ms','ms.store_id','=','i.store_id')
                ->leftJoin('model as m','m.id','=','ms.model_id')
                ->where('i.model_id','=', 'm.id')
                ->where('m.status','=', '1')
                ->where('ms.status','=', '1')
                ->where("i.created_at","=",function($query) {
                    $query->select(DB::raw("si.created_at FROM inventory AS si WHERE si.model_id = i.model_id AND si.store_id = i.store_id AND si.status=1 ORDER BY si.created_at DESC LIMIT 1)) as stock GROUP BY stock.model_id"));
                });

它给我以下错误: -

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1 (SQL: select sum(stock.total_in_stock) as total_in_stock,stock.name,stock.inventory_id FROM ( SELECT i.store_id,i.model_id,i. total_in_stock,i.id as inventory_id, m.* from `inventory` as `i` left join `model_store` as `ms` on `ms`.`store_id` = `i`.`store_id` left join `model` as `m` on `m`.`id` = `ms`.`model_id` where `i`.`model_id` = m.id and `m`.`status` = 1 and `ms`.`status` = 1 and `i`.`created_at` = (select si.created_at FROM inventory AS si WHERE si.model_id = i.model_id AND si.store_id = i.store_id AND si.status=1 ORDER BY si.created_at DESC LIMIT 1 )) as stock GROUP BY stock.model_id)) 

最后需要2个右括号,并给出上述错误。请帮我在laravel中编写上面的SQL查询。

1 个答案:

答案 0 :(得分:0)

回答你在瓷砖中的问题:需要修复的子查询:

->where("i.created_at", function($query) {
    $query->from('inventory as si')
          ->selectRaw('max(si.created_at)')
          ->whereRaw('si.model_id = i.model_id AND ...');
});

但是,为了在from子句中创建子查询,您需要传递原始查询,因此整个代码需要一些toSql()setBindings(...),这很麻烦

为了获得 问题的答案,请更好地描述问题本身。