2014-11-21 36 views
12

我有以下雄辩查询(这是由更where S和orWhere小号。因此要对这个明显的迂回的方式查询的简化版本 - 理论是什么是最重要):如何使用Laravel雄辩创建子查询?

$start_date = //some date; 

$prices = BenchmarkPrice::select('price_date', 'price') 
->orderBy('price_date', 'ASC') 
->where('ticker', $this->ticker) 
->where(function($q) use ($start_date) { 

    // some wheres... 

    $q->orWhere(function($q2) use ($start_date){ 
     $dateToCompare = BenchmarkPrice::select(DB::raw('min(price_date) as min_date')) 
     ->where('price_date', '>=', $start_date) 
     ->where('ticker', $this->ticker) 
     ->pluck('min_date'); 

     $q2->where('price_date', $dateToCompare); 
    }); 
}) 
->get(); 

正如你可以看到我pluck该日或之后我start_date发生的最早日期。这会导致运行一个单独的查询以获取此日期,然后将其用作主查询中的参数。有没有一种雄辩的方式将查询嵌入到一起形成子查询,因此只有1个数据库调用而不是2个?

编辑:每@亚雷克的回答

因为这是我的查询:

$prices = BenchmarkPrice::select('price_date', 'price') 
->orderBy('price_date', 'ASC') 
->where('ticker', $this->ticker) 
->where(function($q) use ($start_date, $end_date, $last_day) { 
    if ($start_date) $q->where('price_date' ,'>=', $start_date); 
    if ($end_date) $q->where('price_date' ,'<=', $end_date); 
    if ($last_day) $q->where('price_date', DB::raw('LAST_DAY(price_date)')); 

    if ($start_date) $q->orWhere('price_date', '=', function($d) use ($start_date) { 

     // Get the earliest date on of after the start date 
     $d->selectRaw('min(price_date)') 
     ->where('price_date', '>=', $start_date) 
     ->where('ticker', $this->ticker);     
    }); 
    if ($end_date) $q->orWhere('price_date', '=', function($d) use ($end_date) { 

     // Get the latest date on or before the end date 
     $d->selectRaw('max(price_date)') 
     ->where('price_date', '<=', $end_date) 
     ->where('ticker', $this->ticker); 
    }); 
}); 
$this->prices = $prices->remember($_ENV['LONG_CACHE_TIME'])->get(); 

orWhere块导致查询中的所有参数,突然变得不带引号的。例如。 WHERE price_date >= 2009-09-07。当我删除orWheres查询工作正常。为什么是这样?

回答

16

这是你怎么做,其中一个子查询:

$q->where('price_date', function($q) use ($start_date) 
{ 
    $q->from('benchmarks_table_name') 
    ->selectRaw('min(price_date)') 
    ->where('price_date', '>=', $start_date) 
    ->where('ticker', $this->ticker); 
}); 

不幸的是orWhere需要明确规定$operator,否则会引发一个错误,那么你的情况:

$q->orWhere('price_date', '=', function($q) use ($start_date) 
{ 
    $q->from('benchmarks_table_name') 
    ->selectRaw('min(price_date)') 
    ->where('price_date', '>=', $start_date) 
    ->where('ticker', $this->ticker); 
}); 

编辑:你实际上需要在闭包中指定from,否则它不会构建正确的查询。

+3

加1 - 这是正确的答案。一旦OP接受这个答案,我会立即删除它。 – 2014-11-21 16:56:18

+0

再次看起来不错,除了绑定不是很对。我发现'$ this-> ticker'参数被输入到未加引用的查询中,导致错误。例如。 '... AND ticker = ukc0tr01 INDEX)...' – harryg 2014-11-21 17:19:30

+0

日期也一样:'WHERE price_date <= 2014-07-31'。为什么在日期前没有引号? – harryg 2014-11-21 17:21:24