我有以下 Eloquent 查询(这是一个简化版本的查询,它由更多的 where
和 orWhere
组成,因此明显的迂回方式这 - 理论才是最重要的):
$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();
如您所见,我选取
在我的start_date
当天或之后发生的最早日期。这导致运行单独的查询以获取此日期,然后将其用作主查询中的参数。有没有一种方法可以将查询嵌入在一起形成一个子查询,从而只调用 1 个数据库而不是 2 个?
编辑:
根据@Jarek 的回答,这是我的查询:
$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
block 导致查询中的所有参数突然变得不带引号。例如。 WHERE
price_date>= 2009-09-07
。当我删除 orWheres
时,查询工作正常。这是为什么?
最佳答案
这就是你执行子查询的方式:
$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
,否则将无法构建正确的查询。
关于php - 如何使用 Laravel Eloquent 创建子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27064678/