如果transaction表中没有记录,我试图返回零值。现在,如果特定预算没有交易,那么我什么也得不到。这是我现在的询问。非常感谢。下面是一个例子,当我不需要交易时,我需要它返回0作为燃料。我澄清了。
预算表
_____________
id | name
1 | Groceries
2 | Fuel
交易表
__________________
id | Category_id | Amount
1 | 1 | 30
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();
答案 0 :(得分:0)
试试这个:
name
说明:最初$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;
}
为空$budgets
,运行查询后,如果数组仍为空,则表示查询不返回任何数据。在那种情况下返回0,否则返回数据。
答案 1 :(得分:0)
您应该使用COALESCE功能:
替代
DB::raw('SUM(transactions.amount) / budgets.amount * 100 as percent'),
'budgets.category'
与
DB::raw('COALESCE(SUM(transactions.amount), 0) / budgets.amount * 100 as percent'),
'budgets.category'