简体   繁体   English

如何检查日期字段是否已过期 (Laravel/Lumen)

[英]How to check if a datefield is expired (Laravel/Lumen)

I have a table called events and events expire.我有一个名为 events 和 events expire 的表。 if their dates and time is up how do i check in my controller if the dateTime field from and to are up if that event time is up i want to set the expired field to 1如果他们的日期和时间已到,我如何检查我的控制器,如果从和到的日期时间字段已启动,如果该事件时间已到,我想将过期字段设置为 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’);

});
}

You would compare it to the current datetime like: 您可以将其与当前日期时间进行比较,例如:

if (now()->gte($clubEvent->to)) {
    // the event is expired
} else {
    // not expired
}

Here are the Carbon comparison functions. 这是Carbon 比较功能。

Update the expired field like: 更新过期字段,例如:

$clubEvent->update([
     'expired' => now()->gte($clubEvent->to)
]);

You should be able to just run an update query on your model: 您应该能够只对模型运行更新查询:

ClubEvent::whereRaw('to < NOW()')
    ->where('expired', false)
    ->update(['expired' => true]);

If however, you want to actually find events that are in the past, but have not been expired, you can find them with another query: 但是,如果您实际上想查找过去但尚未过期的事件,则可以使用另一个查询找到它们:

$events = ClubEvent::whereRaw('to < NOW()')
    ->where('expired', false)
    ->get();

This could also be created as a query scope on your model: 也可以将其创建为模型的查询范围:

public function scopeIsPast($query)
{
    return $query->whereRaw('to < NOW()');
}

You could then use your query scope instead: 然后,您可以使用查询范围:

ClubEvent::isPast()->update(['expired' => true]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM