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

问题描述 投票:0回答:1

我有两个桌子。 productinventory。我想与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。

php postgresql laravel-5.7
1个回答
0
投票

通过这种方式可以设置可用库存的默认值

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();
© www.soinside.com 2019 - 2024. All rights reserved.