Laravel Eloquent - created_at 是 X 天前的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46793741/
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
Laravel Eloquent - where created_at is X days ago
提问by Lovelock
I have an array of days that I want to check against for trials ending in Laravel Spark:
我有一系列的日子要检查以 Laravel Spark 结束的试验:
$trialIntervals = [10, 5, 3, 1, 0];
I fetch all teams and then check if their trial_ends_at date one of the intervals using diffInDays:
我获取所有团队,然后使用 diffInDays 检查他们的 trial_ends_at 日期是否为间隔之一:
$daysTillTrialEnds = Carbon::parse($team->trial_ends_at)->diffInDays(Carbon::now());
I then check if this value is already an existing result in the database and in the intervals:
然后我检查这个值是否已经是数据库和间隔中的现有结果:
if ( in_array($daysTillTrialEnds, $trialIntervals) && !TrialEndingNotification::where('team_id', $team->id)->where('days_notified_at', $daysTillTrialEnds)->count() ) {
// not yet been added to db
}
I have a field called 'days_notified_at' that I am using the check if I have already added the row and notified the customer. However that field is never used again and I would rather reference the created_at date and remove the field.
我有一个名为“days_notified_at”的字段,如果我已经添加了行并通知客户,我正在使用检查。但是,该字段不再使用,我宁愿引用 created_at 日期并删除该字段。
My question is how I essentially do this:
我的问题是我基本上是如何做到这一点的:
->where(Carbon::parse('created_at')->diffInDays(Carbon::now()), $daysTillTrialEnds)
Without getting this error:
没有收到此错误:
DateTime::__construct(): Failed to parse time string (created_at) at position 0 (c): The timezone could not be found in the database
The aim is that the where will only show rows that have a created_at date that is X days ago.
目的是 where 将只显示具有 X 天前 created_at 日期的行。
回答by Walter
Use WhereRaw
使用 WhereRaw
->whereRaw('DATEDIFF(CURDATE(),STR_TO_DATE(created_at, '%Y-%m-%d'))'), $daysTillTrialEnds)
回答by Vipin Kumar
->where(Carbon::parse('created_at')->diffInDays(Carbon::now()), $daysTillTrialEnds)
to should be like
应该像
->where(Carbon::parse($item->created_at)->diffInDays(Carbon::now()), $daysTillTrialEnds)
回答by ATechGuy
Laravel will automatically turn the "created_at" into a carbon object so you don't have to parse it.
Laravel 会自动将“created_at”转换成一个 carbon 对象,这样你就不必解析它了。
`$items->where('created_at')->diffInDays(Carbon::now(), $daysTillTrialEnds)'
Should work for you
应该为你工作
回答by LorenzoBerti
Have you tried something like:
你有没有试过这样的事情:
$dayAgo = 6 // where here there is your calculation for now How many days
$dayToCheck = Carbon::now()->subDays($dayAgo);
$model->whereDate("created_at", =, $dayToCheck);