laravel 最近 30 天的雄辩选择记录

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

Eloquent select records form last 30 days

laraveleloquent

提问by jOpacic

I having a list of records that have a date (like 11/5/2013, that's a MDY formt), but the dates are VARCHARfields.

我有一个包含日期的记录列表(例如11/5/2013,这是一个 MDY 格式),但日期是VARCHAR字段。

I want to select all the records that are in the last 30 days, but don't know how to cast them to date format, as I get NULL in dates field.

我想选择过去 30 天内的所有记录,但不知道如何将它们转换为日期格式,因为我在日期字段中得到 NULL。

I'm using Laravel and Eloquent ORM, how can I accomplish this?

我正在使用 Laravel 和 Eloquent ORM,我该如何实现?

回答by Anam

You need an accessor in your model.

您的模型中需要一个存取器。

Assume your have a datesfield in your table.

假设您dates的表中有一个字段。

public function getDatesAttribute($value)
   {
     $this->attributes['dates'] = Carbon::createFromFormat('m/d/Y', $value);
   }

The above function will convert the date from string to Carbon object. By default Laravel support Carbon.

上面的函数会将日期从字符串转换为 Carbon 对象。默认 Laravel 支持 Carbon。

Now from you controller:

现在从你的控制器:

$test = Test::where('dates', '>=', Carbon::now()->subMonth())->get();

I haven't tested the code but should work. :)

我还没有测试代码,但应该可以工作。:)