Table 状态 laravel

Table status in laravel

我很想为我的 laravel table 添加 table 状态。我想要这样一种情况,当 table 被创建时,它会拥有 table 状态“"new then after two day it's going to have a status "old”

您不需要为此创建新专栏。您可以使用 created_by 来计算它是否是 new/old。模型上的 accessor function 使它更容易:

public function getStatusAttribute() {
    return $this->created_at->gt(now()->subDays(2)) ? 'new' : 'old';
}

然后您可以访问该值作为 $model->status

如果您正在使用 timestamps,则 Laravel 中不需要新的 table/column。您可以检查 created_at 时间戳并与今天进行比较;如果 diffInDays() 大于 2,则 return "old" 否则 return "new"。例如,在您的 model:

Example.php:

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Example extends Model {
  public function getStatusAttribute(){
    if(Carbon::now()->diffInDays($this->created_at) > 2){
      return "old";
    }
    return "new";
  }
}

然后,您可以查询您的模型并检查 status 属性:

$example = Example::first();
dd($example->status); // Will be `"old"` or `"new"`