[英]How to check if a datefield is expired (Laravel/Lumen)
我有一个名为 events 和 events expire 的表。 如果他们的日期和时间已到,我如何检查我的控制器,如果从和到的日期时间字段已启动,如果该事件时间已到,我想将过期字段设置为 1
public function up()
{
Schema::create(‘club_events’, function (Blueprint $table) {
$table->increments(‘id’);
$table->string(‘event_name’);
$table->string(‘description’);
$table->boolean(‘special_events’);
$table->decimal(‘event_price’);
$table->dateTime(‘from’)->nullable();
$table->dateTime(‘to’)->nullabe();
$table->boolean(‘expired’)->nullable();
$table->integer(‘club_id’)->unsigned();
$table->timestamps();
$table->foreign(‘club_id’)
->references(‘id’)->on(‘club’)
->onDelete(‘cascade’);
});
}
您可以将其与当前日期时间进行比较,例如:
if (now()->gte($clubEvent->to)) {
// the event is expired
} else {
// not expired
}
这是Carbon 比较功能。
更新过期字段,例如:
$clubEvent->update([
'expired' => now()->gte($clubEvent->to)
]);
您应该能够只对模型运行更新查询:
ClubEvent::whereRaw('to < NOW()')
->where('expired', false)
->update(['expired' => true]);
但是,如果您实际上想查找过去但尚未过期的事件,则可以使用另一个查询找到它们:
$events = ClubEvent::whereRaw('to < NOW()')
->where('expired', false)
->get();
也可以将其创建为模型的查询范围:
public function scopeIsPast($query)
{
return $query->whereRaw('to < NOW()');
}
然后,您可以使用查询范围:
ClubEvent::isPast()->update(['expired' => true]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.