簡體   English   中英

如何檢查日期字段是否已過期 (Laravel/Lumen)

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM