为了账号安全,请及时绑定邮箱和手机立即绑定

如果 laravel 中不存在连接表数据,如何设置默认值?

如果 laravel 中不存在连接表数据,如何设置默认值?

PHP
眼眸繁星 2022-10-28 09:58:33
我有两张桌子。product和inventory。我想 LEFT JOIN product。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。
查看完整描述

1 回答

?
开满天机

TA贡献1786条经验 获得超12个赞

这样,您可以设置可用库存的默认值。


当库存不可用时,这将为零。


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


查看完整回答
反对 回复 2022-10-28
  • 1 回答
  • 0 关注
  • 103 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信