我的查询有多个子查询,其中包含我试图在Laravel模型中构建的参数。
我对Laravel 4很陌生,所以我真的希望得到一些“最佳”方法的帮助。
我需要重现的查询是:
Select userId from facultyAvailability
where
:startDate between startDate and endDate
and :endDate between startDate and endDate
and userId NOT IN(
Select
userId
from
schedulerTrialSchedule
inner join `review`
on eventId=lectureId
where
trialId = :trialId
and (
startDate between :startDate and :endDate
or endDate between :startDate and :endDate
)
)
AND userId IN (
SELECT userId
from
faculty2FacultyCategory
where
categoryId in(:categoryIdList)
)
我真的不确定连接在一起构建它的方法。任何帮助将不胜感激。
答案 0 :(得分:2)
好吧,经过一些反复试验,我认为我找到了正确的解决方案。
我正在使用Eloquent的查询范围功能。在有问题的模型上,我将范围定义为:
public function scopeAvailable($query, $trialId, UnscheduledEvent $event)
{
$query->whereRaw('? BETWEEN startDate AND endDate', array($event->startDate))
->whereRaw('? BETWEEN startDate AND endDate', array($event->endDate))
->whereIn(
'userId', function ($query) use ($trialId, $event) {
$query->select('userId')
->from('schedulerTrialSchedule')
->join('review', 'eventId', '=', 'lectureId')
->where('trialId','=',$trialId)
->where(
function ($query) use ($event) {
$query->whereBetween('startDate', array($event->startDate, $event->endDate))
->orWhereBetween('endDate', array($event->startDate, $event->endDate));
}
);
}
,'and',true);
return $query;
}
此范围产生的查询如下所示:
select *
from `facultyAvailability`
where
? BETWEEN startDate AND endDate
and ? BETWEEN startDate AND endDate
and `userId` not in (
select `userId`
from `schedulerTrialSchedule`
inner join `review` on `eventId` = `lectureId`
where `trialId` = ?
and (`startDate` between ? and ? or `endDate` between ? and ?))
这正是我所需要的。我在这里发布这个仅供参考,以防其他人需要知道如何解决这个问题。
我不得不说,我对Eloquent / Fluent能够应对这种情况印象深刻,而不必使用一堆原始SQL。我根本不得不使用原始SQL的唯一原因是因为whereBetween
似乎无法处理使用值而不是列的第一个参数与列之间作为第二和第三个参数,即'2013-08-09' BETWEEN column1 AND column2