php whereBetween Dates in laravel 4 eloquent

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26082043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:08:44  来源:igfitidea点击:

whereBetween Dates in laravel 4 eloquent

phplaravellaravel-4eloquent

提问by Md. Sahadat Hossain

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. I use Eloquent

现在我如何在laravel 4. 我用Eloquent

回答by tigerDisplayName

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

也许你可以试试这个

回答by Godfrey Makori

  $count =  TokenLog::whereBetween(DB::raw('date(created_at)'), [$start_date, $end_date])->get();

回答by damiani

In your example, you're checking both from_dateand to_datefor 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.phpmodel:

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');

回答by Sahib J. Leo

You can use whereRaw()to add a raw where clause to the query, for example:

您可以使用whereRaw()向查询添加原始 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 readablecode, 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.

但我不太确定这是否有效,试一试。