【发布时间】:2019-11-27 09:01:52
【问题描述】:
谁能帮助解决这个查询。查询返回“j.code”和“accounts.title”的空结果。而且我 100% 确定它应该返回结果。我认为我的左连接丢失了一些东西。这是在左连接中使用左连接的正确方法吗?
$query = DB::table('autostk')
->where('autostk.branchid', $branch_id)
->where('autostk.itemcode',$request->itemcode)
->whereDate('autostk.date','<=',$request->tdate)
->leftjoin('journal AS j', function($join) use ($branch_id) {
$join->on('autostk.refno', '=', 'j.vno')
->where('j.code', '>=', 100)
->where('j.branchid', $branch_id)
->where('j.vtype', '=', 'autostk.vtype')
->leftjoin('accounts', 'j.code', '=', 'accounts.code')
->where('accounts.branchid', $branch_id);
})
->select('j.code','accounts.title','autostk.*')
->orderBY('date')->get()
->map(function ($item, $key) {
return (array) $item;
})
->all();
生成的原始查询是:
select `j`.`code`, `accounts`.`title`, `autostk`.* from `autostk`
left join (`journal` as `j` left join `accounts` on `j`.`code`=`accounts`.`code`)
on `autostk`.`refno` = `j`.`vno` and `j`.`code` >= ? and `j`.`branchid` = ?
and `j`.`vtype` = ? and `accounts`.`branchid` = ? where `autostk`.`branchid` = ?
and `autostk`.`itemcode` = ? and date(`autostk`.`date`) <= ? order by
`autostk`.`date` asc
更新: 在检查 QueryLog 时,我注意到 'j'.'vtype' 的绑定是“autostk.vtype” 使用“autostk.vtype”在工作台中应用查询返回空结果。 但是当我将其更改为 'autostk'.'vtype' 时,结果正确显示。 如何在 Laravel Eloquent 中进行这种更改?
【问题讨论】:
-
如果您先尝试使用
toSql()函数调试您的查询会更容易。 -
如果您确定列应该始终包含结果,为什么还要进行左连接?
-
我已经用原始查询更新了我的帖子。
标签: laravel eloquent laravel-5.8