【问题标题】:convert mysql to query to laravel query将 mysql 转换为查询到 laravel 查询
【发布时间】:2018-06-13 11:26:05
【问题描述】:

您好,我正在尝试将此 mysql 查询转换为 laravel 查询,但仍然没有成功。你能帮忙把这个mysql查询转换成laravel查询吗?

Mysql查询如下

select *,SUM(pp.starting_balance) as total from (select `aa`.*, 
GROUP_CONCAT( CONCAT(cc.purchasedescription," (",bb.quantity,")") SEPARATOR " , ") as bundle_item 
from `composite_inventories` as aa 
left join 
`composite_has_inventories` as bb on `aa`.`id` = `bb`.`composite_inventory_id` 
left join 
`inventories` as cc on `bb`.`inventory_id` = `cc`.`id` 
where 
`aa`.`subscriber_id` = '2'
group by 
`aa`.`id`) as tt left join `composite_has_warehouses` as pp on `tt`.`id` = `pp`.`composite_inventory_id` group by pp.composite_inventory_id

我尝试如下构建但无法正常工作

$row = DB::table('composite_inventories')->select('composite_inventories.*',
            DB::raw('SUM(composite_has_warehouses.starting_balance) as total')
            DB::raw('GROUP_CONCAT( CONCAT(inventories.purchasedescription," (",composite_has_inventories.quantity,")") SEPARATOR " , ") as bundle_item')
            )
            ->leftJoin('composite_has_inventories', 'composite_inventories.id', '=', 'composite_has_inventories.composite_inventory_id')
            ->leftJoin('inventories', function($join) {
                $join->on('composite_has_inventories.inventory_id', '=', 'inventories.id');
            })

            ->where('composite_inventories.subscriber_id',$subscriber_id)
            ->groupBy('composite_inventories.id')
            ->leftJoin('composite_has_warehouses', 'composite_inventories.id', '=', 'composite_has_warehouses.composite_inventory_id')
            ->get();

【问题讨论】:

  • 显示你尝试过的代码。
  • 你试过什么?无论如何 - 对于像这样的复杂查询,使用原始 SQL 通常比使用 Laravel 的查询构建器更具可读性。 laravel.com/docs/5.6/database#running-queries
  • 我已经发布了我在 laravel 中尝试过的查询
  • 不工作到底是什么意思?任何错误或输出不符合预期
  • 我无法在我的 laravel 查询中获得与 mysql 查询相同的结果。在 mysql 查询中,它为捆绑项目返回正确的值,但在 laravel 查询中,它为捆绑项目返回错误的值

标签: php mysql laravel laravel-query-builder


【解决方案1】:

您可以使用DB::select() 方法并将原始查询作为字符串放置:

DB::select("select *,SUM(pp.starting_balance) as total from (select `aa`.*,
DB::raw('GROUP_CONCAT( CONCAT(cc.purchasedescription,' (',bb.quantity,')') SEPARATOR ' , ') as bundle_item ')
from `composite_inventories` as aa 
left join 
`composite_has_inventories` as bb on `aa`.`id` = `bb`.`composite_inventory_id` 
left join 
`inventories` as cc on `bb`.`inventory_id` = `cc`.`id` 
where 
`aa`.`subscriber_id` = '2'
group by 
`aa`.`id`) as tt left join `composite_has_warehouses` as pp on `tt`.`id` = `pp`.`composite_inventory_id` group by pp.composite_inventory_id");

【讨论】:

  • 好的,我可以使用原始查询,但我的 where 条件在此查询中是动态的。如果设置了状态,那么我的查询将在 where 条件下具有状态。
  • 您可以将其作为 where 条件,如下所示: 和 IF('" . $condition . "' = some_value, put where clause condition here', 1) 这将确保如果条件满足,然后将条件添加到查询中,否则返回 1 (true),这不会影响您的查询。让我知道这是否有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-31
  • 1970-01-01
  • 2019-03-09
  • 1970-01-01
相关资源
最近更新 更多