我需要将管理员的总和添加到交易中。事务被分成多个表,现在我想分别从两个表中获取总数。结果我得到的结果是荒谬的高。我不确定是我的查询乘以某处的值。
User::select('user.name as name',
DB::raw('sum(CASE WHEN current.amount > 0 THEN current.amount END) as current_positive'),
DB::raw('sum(CASE WHEN current.amount < 0 THEN current.amount END) as current_negative'),
DB::raw('sum(CASE WHEN cash.amount > 0 THEN cash.amount END) as cash_positive'),
DB::raw('sum(CASE WHEN cash.amount < 0 THEN cash.amount END) as cash_negative')
)->leftjoin('current_transaction as current', 'current.created_by', '=', 'user.id')
->leftjoin('cash_transaction as cash', 'cash.created_by', '=', 'user.id')
->whereBetween('current.created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
->whereBetween('cash.created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
->where('user.type', 3)
->groupBy('user.name')
->get();
我正在尝试使用M Khalid的解决方案,以下是错误消息:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError:类型错误:传递给Illuminate \ Database \ Query \ Builder的参数1 :: mergeBindings()必须是Illuminate \ Database \ Query \ Builder的实例
Symfony \ Component \ Debug \ Exception \ FatalThrowableError:类型错误:参数1传递给Illuminate \ Database \ Query \ Builder :: mergeBindings()必须是Illuminate \ Database \ Query \ Builder的实例,给定数组
ErrorException:类Illuminate \ Database \ Eloquent \ Builder的对象无法转换为字符串
答案 0 :(得分:1)
由于左边连接,你得到的金额错误,每个连接表可能每个用户有多行,这使得金额远远高于原始金额,为了解决这个问题你需要计算这些金额在indvidual子句中,然后加入这些与主要有点像
// For current_transaction
$CUT = CurrentTransaction::query()
->select('created_by',
DB::raw('sum(CASE WHEN amount > 0 THEN amount END) as current_positive'),
DB::raw('sum(CASE WHEN amount < 0 THEN amount END) as current_negative')
)
->from('current_transaction')
->whereBetween('created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
->groupBy('created_by');
$CUTSql = $CUT->toSql();
// For cash_transaction
$CAT = CashTransaction::query()
->select('created_by',
DB::raw('sum(CASE WHEN amount > 0 THEN amount END) as cash_positive'),
DB::raw('sum(CASE WHEN amount < 0 THEN amount END) as cash_negative')
)
->from('cash_transaction')
->whereBetween('created_at', [$start_date->format('Y-m-d'), $end_date->format('Y-m-d')])
->groupBy('created_by');
$CATSql = $CAT->toSql();
// Main query
User::select('user.name as name','cu.*','ca.*')
->leftjoin(DB::raw('(' . $CUTSql. ') AS cu'),function($join) use ($CUT) {
$join->on('user.id', '=', 'cu.created_by');
/* ->addBinding($CUT->getBindings());*/
})
->leftjoin(DB::raw('(' . $CATSql. ') AS ca'),function($join) use ($CAT) {
$join->on('user.id', '=', 'ca.created_by');
/* ->addBinding($CAT->getBindings()); */
})
->where('user.type', 3)
->mergeBindings($CUT) /* or try with ->mergeBindings($CUT->getBindings()) */
->mergeBindings($CAT) /* or try with ->mergeBindings($CAT->getBindings()) */
->get();
在laravel上面做的很复杂,就像每个子句获取sql和query构建器对象然后在主查询中使用它们有点像下面
{{1}}