[英]whereBetween Dates in laravel 4 eloquent
I have a query like that 我有这样的查询
SELECT * FROM `sp_price` WHERE (`from_date` between '2014-08-15' and '2014-09-18') || (`to_date` between '2014-08-15' and '2014-09-18')
Now how I can convert this query in laravel 4
. 现在我如何在
laravel 4
转换此查询。 I use Eloquent
我用
Eloquent
DB::table(sp_price)
->whereBetween('from_date',array('2014-08-15','2014-08-18'))
->orWhereBetween('to_date',array('2014-08-15','2014-08-15'))
->get();
maybe you can try this 也许你可以试试这个
$count = TokenLog::whereBetween(DB::raw('date(created_at)'), [$start_date, $end_date])->get();
In your example, you're checking both from_date
and to_date
for the same range of dates...if this will always be the case, you can make this query a bit more "eloquent": 在您的示例中,您同时检查
from_date
和to_date
的相同日期范围...如果始终如此,您可以使此查询更加“雄辩”:
In the SpPrice.php model: 在SpPrice.php模型中:
public function getPriceByDate($fromDate, $toDate)
{
$range = [$fromDate, $toDate];
return $this
->whereBetween('from_date', $range)
->orwhereBetween('to_date', $range)
->get();
}
Then, to call this method from a controller: 然后,从控制器调用此方法:
$prices = new SpPrice;
$price = $prices->getPriceByDate('2014-08-15', '2014-09-18');
You can use whereRaw()
to add a raw where clause to the query, for example: 您可以使用
whereRaw()
向查询添加raw where子句,例如:
$results = SpPrice::whereRaw("('2014-08-15' between `from_date` and `to_date`) || ('2014-09-18' between `from_date` and `to_date`)")->get();
Or maybe you can use DB::raw()
as first argument of whereBetween()
, but I'm not sure if it's possible, in that case you can use orWhere()
with a closure to write a more readable code, for example: 或者你可以使用
DB::raw()
作为whereBetween()
第一个参数,但是我不确定它是否可能,在这种情况下你可以使用带有闭包的orWhere()
来编写更易读的代码,例如:
SpPrice::whereBetween(DB::raw('"2014-08-15"'), ['from-date', 'to_date'])->orWhere(function($q)
{
$q->whereBetween(DB::raw('"2014-09-18"'), ['from-date', 'to_date']);
});
But I'm not quite sure if this works, give it a try. 但我不确定这是否有效,试一试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.