1

我有一个查询,其中包含多个子查询,其中包含我试图在 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)
  )

我真的不确定将哪些方法链接在一起来构建它。任何帮助将不胜感激。

4

1 回答 1

2

好吧,经过反复试验,我想我找到了正确的解决方案。

我正在使用 Eloquent 的 Query Scope 功能。在有问题的模型上,我将范围定义为:

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

于 2013-08-18T17:43:47.590 回答