简体   繁体   English

Laravel SQl:如果不存在任何记录,如何返回0值

[英]Laravel SQl: How to return 0 value if no record exists

I am trying to return a value of zero if no record in the transactions table exists. 如果事务表中没有记录,我将尝试返回零值。 Right now if no transactions exists for a specific budget then I get nothing back. 现在,如果没有针对特定预算的交易,那么我什么也得不到。 This is my query right now.Any help is appreciated. 这是我现在的查询。感谢您的帮助。 Below is an example of when I would need it to return 0 for fuel since no transaction exists for it. 下面是一个示例,当我不要求它返回任何燃料时,何时需要它返回0。 I clarified. 我澄清了

budgets table 预算表

_____________
id | name
1  | Groceries
2  | Fuel

transactions table 交易表

__________________
id | Category_id | Amount
1  | 1           | 30

Laravel code Laravel代码

 $budgets = Budget::join('transactions', 'budgets.id', '=', 'transactions.category','left outer')
   ->select([
      DB::raw('SUM(transactions.amount) / budgets.amount * 100 as percent'),
                        'budgets.category'
    ])
    ->where('transactions.user_id','=', $authId)
    ->where('budgets.user_id','=',$authId)
    ->whereBetween('transactions.created_at', array($first_day_this_month, $last_day_this_month))
    ->groupBy('budgets.category','budgets.amount')
    ->get();

Try this: 尝试这个:

$budgets = array();
$budgets = Budget::join('transactions', 'budgets.id', '=', 'transactions.category','left outer')
                ->select([
                    DB::raw('SUM(transactions.amount) / budgets.amount * 100 as percent'),
                    'budgets.category'
                ])
                ->where('transactions.user_id','=', $authId)
                ->where('budgets.user_id','=',$authId)
                ->whereBetween('transactions.created_at', array($first_day_this_month, $last_day_this_month))

                ->groupBy('budgets.category','budgets.amount')
                ->get();

if( count($budgets) == 0 )
{
    return 0;
}
else
{
    return $budgets;
}

Explanation: Initially the $budgets is an blank array() , after running the query if still the array is blank means query do not return any data. 说明:最初$budgets是一个空白array() ,在运行查询后,如果该数组仍然为空,则表示查询不返回任何数据。 In that case return 0, otherwise the data array. 在这种情况下,返回0,否则返回数据数组。

You should use COALESCE function: 您应该使用COALESCE函数:

substitute 替代

DB::raw('SUM(transactions.amount) / budgets.amount * 100 as percent'), 
'budgets.category'

with

DB::raw('COALESCE(SUM(transactions.amount), 0) / budgets.amount * 100 as percent'), 
'budgets.category'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM