【问题标题】:Building query with Query Builder or Eloquent in Laravel 4在 Laravel 4 中使用 Query Builder 或 Eloquent 构建查询
【发布时间】:2014-05-18 15:42:55
【问题描述】:

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

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

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

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

    我正在使用 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 似乎无法处理使用值而不是列作为之间的第一个参数,列作为第二个和第三个参数,即 @987654324 @

    【讨论】:

      猜你喜欢
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2014-01-08
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      相关资源
      最近更新 更多