我正在使用Laravel控制器将数据发送到chartist.js。当我尝试将三个表连接在一起以求值总和时,当我连接第三个表时,输出实际上将增加一倍。
以下查询获取了我需要的数据,但是并不能准确地求和
$chart_stats = Transactions::join('customers', 'customers.id', '=', 'transactions.customer_id')
->join('orders', 'orders.customer_id', '=', 'transactions.customer_id')
->distinct()
->select('customers.region', 'transactions.deposit', 'transactions.purchase_total', 'transactions.finance_amount_paid', 'orders.gov_funding_amount')
->whereIn('customers.region', $selected_regions)
->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
->select(
DB::raw('customers.region as region' ),
DB::raw('sum(transactions.deposit) as deposits'),
DB::raw('sum(transactions.purchase_total) as sums'),
DB::raw('sum(transactions.finance_amount_paid) as finance_paid'),
DB::raw('sum(transactions.deposit+transactions.finance_amount_paid) as total_paid'),
DB::raw('sum(orders.gov_funding_amount) as funding')
)
->groupBy('customers.region')
->orderBy('sums', 'asc')
->get();
这将在数组中输出以下内容:
#original: array:6 [▼
"region" => "Region 1"
"deposits" => "5025.40"
"sums" => "52875.00"
"finance_amount_paid" => "0.00"
"total_paid" => "5025.40"
"funding" => "9228.00"
应该是:
#original: array:6 [▼
"region" => "Region 1"
"deposits" => "1706.00"
"sums" => "21271.00"
"finance_amount_paid" => "0.00"
"total_paid" => "1706.40"
"funding" => "3396.00"
答案 0 :(得分:1)
我本来打算对此发表评论,但最好是作为答复。这是一个命题,我可能是错的。有2个可能的答案。
更改这些行:
->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
要:
->whereBetween('transaction.created_at, $from, $to)
或 edit:类型,将数组纠正为数组:
->where([['transactions.created_at', '>', $from], ['transactions.created_at', '<', $to]])
如果这两个条件均成立,则有可能将行选择两次。 distinct()可能不执行预期的操作。您也可以尝试关闭:
->where(function ($query) {
$query->where('transactions.created_at', '>', $from)
->where('transactions.created_at', '<', $to)
->distinct();
})