laravel 如何在 Eloquent 中使用 DATEDIFF 函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18077709/
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-09-14 08:13:56  来源:igfitidea点击:

How to use DATEDIFF function with Eloquent?

phpsqllaraveleloquent

提问by Maciej P?ocki

Here is my code for selecting reservations:

这是我选择预订的代码:

Reservation::select(array(
    'obj_id', 
    'name', 
    'surname',
    'date_from',
    'date_to', 
    'days',
    'status',
    'slug',
    'payable'
));

My question is how to change 'days' to get real diff between date_fromand date_to? I don't have 'days' column in the database, I just want to count them in the SQL query.

我的问题是如何更改“天”以在date_from和之间获得真正的差异date_to?我在数据库中没有“天”列,我只想在 SQL 查询中计算它们。

In pure SQL should be something like that:

在纯 SQL 中应该是这样的:

SELECT DATEDIFF('date_from, date_to) AS Days FROM RESERVATIONS;

How can I do that using Eloquent?

我怎样才能使用 Eloquent 做到这一点?

回答by Abishek

You can use DB::rawfor this.

您可以为此使用DB::raw

Reservation::select(array(
            'obj_id', 'name', 'surname',
            'date_from', 'date_to', 
            'days',
            'status', 'slug', 'payable', 
            DB::raw("DATEDIFF(date_from,date_to)AS Days"))
))