我有两张桌子。product
和inventory
。我想 LEFT JOINproduct
与inventory
. 还有一个基于inventory.stock 的求和操作。
我的代码如下,
DB::table('product')
->leftjoin('inventory','product.id','=','inventory.product_id')
->select('product.id as id',
'product.name as name',
'product.color as color',
'product.unit_price as unit_price',
DB::raw('SUM(inventory.stock)::integer as available_stock'))
->groupBy('product.id')
->get();
我的问题是有很多产品在库存表中没有行。在那种情况下,available_stock
它给了我null
。而不是null
我想显示一个默认字符串。诸如“无库存”或“0”之类的东西。我怎样才能做到这一点?
我正在使用 postgresql。
通过这种方式,您可以设置可用库存的默认值。
当库存不可用时,这将给出零。
DB::table('product')
->leftjoin('inventory','product.id','=','inventory.product_id')
->select('product.id as id',
'product.name as name',
'product.color as color',
'product.unit_price as unit_price',
DB::raw('(case when inventory.product_id is null then 0 else SUM(inventory.stock)::integer end) as available_stock'))
->groupBy('product.id')
->get();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句