比较数据库日期和日期
我要检查数据库日期字段是否少于5天
我尝试了Carbon类,该类以整数形式输出值,而MySQL数据库则以字符串或对象形式返回值
$ticket = Tickets::select('created_at')->where('id','=',$id)->get();
我要检查日期的结果是否少于5天 例如,如果当前结果日期为01-05-2019,则消息应为“机票早于5天”
答案 0 :(得分:0)
这应该为您工作。这将返回与今天的日期差。
$ticket = Tickets::selectRaw('abs(datediff(created_at,"'.\Carbon\Carbon::now().'")) as day')->where('id','=',$id)->first();
答案 1 :(得分:0)
我认为您可以将当前日期更改为少于5天并进行比较
$date = new DateTime;
$date->modify('-5 days');
$formatted_date = $date->format('Y-m-d H:i:s');
$ticket = Tickets::where('created_at', $formatted_date)->where('id','=',$id)->first();
如果您只想忽略时间戳并比较日期,则可能需要
$formatted_date = $date->format('Y-m-d');
$ticket = Tickets::where(Date('created_at'), $formatted_date)->where('id','=',$id)->first();
我还没有测试它,但是看来这些代码对您来说应该可以正常工作。
答案 2 :(得分:0)
对不起,我迟到了几天之前也遇到了同样的情况
我已经创建了模型作用域
有关范围的更多信息
https://laravel.com/docs/5.8/eloquent#query-scopes
https://medium.com/@janaksan_/using-scope-with-laravel-7c80dd6a2c3d
因此,将此范围方法添加到map()
Class A {
String name;
List<C> instances;
}
class B {
String name;
List<D> instances;
}
Converter<A,B> getConverter() {
return context -> (
Destination dest = context.getDestination();
Source src = context.getSource();
dest.setName(src.getName());
map(src.getInstances() , dest.getInstances());
return dest;
)
}
所以现在我们完成了方法
现在在您的控制器中
Ticket
这是生成的查询日志
/**
* Scope a query to only include the last n days records
*
* @param \Illuminate\Database\Eloquent\Builder $query
* @return \Illuminate\Database\Eloquent\Builder
*/
public function scopeWhereDateOccurs($query, $fieldName, $upToDate,$noOfDays = 5)
{
$startFrom = \Illuminate\Support\Carbon::parse($upToDate)->toDateTimeString();
$endUpTo = \Illuminate\Support\Carbon::createFromDate( $startFrom)->subDays( $noOfDays)->toDateTimeString();
return $query->whereDate($fieldName, '>=', $startFrom)->whereDate($fieldName, '<=', $endUpTo);
}
并且我正在使用软删除,因此将 deleted_at` IS NULL 添加到所有查询生成器