我有两个桌子。 product
和inventory
。我想与product
一起加入inventory
。还有一个基于库存。库存的求和操作。
我的代码在下面,
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();