我想在laravel 5.2中获得与mysql相同的结果:
select a3.user_id,sum(a3.task_hour)
from activities a3
where id not in
( select a1.id from activities a1 inner join
(SELECT * FROM `activities` where validated = 1) a2
on a1.user_id = a2.user_id and a1.project_id = a2.project_id where a1.validated = 0)
group by a3.user_id
因此,为了清楚地了解代码,我首先尝试获得以下内容:
(SELECT * FROM `activities` where validated = 1) a2
用这个
$activity_onlyFromOTL = DB::table('activities AS a2');
$activity_onlyFromOTL->select('a2.id','a2.year','a2.month','a2.user_id','a2.project_id','a2.task_hour')->where('a2.from_otl','=','1');
对于第二部分,我有这个:
( select a1.id from activities a1 inner join
(SELECT * FROM `activities` where validated = 1) a2
on a1.user_id = a2.user_id and a1.project_id = a2.project_id where a1.validated = 0)
为了清楚起见,我尝试将第一个变量用于第二个语句,以便我可以更好地阅读它:
$activity_whereOTLandNonOTL = DB::table('activities AS a1');
$activity_whereOTLandNonOTL->select('a1.id');
$activity_whereOTLandNonOTL->join($activity_onlyFromOTL, function ($join) {
$join->on('a1.user_id', '=', 'a2.user_id')->on('a1.project_id', '=', 'a2.project_id');
});
$activity_whereOTLandNonOTL->where('a1.validated', '=' , '0');
但是当我尝试为那个获取toSql时,我收到错误:
ErrorException in Grammar.php line 39:
Object of class Illuminate\Database\Query\Builder could not be converted to string
我如何以这种方式工作,以便它是一个更清晰的代码?