Home > PHP Framework > Laravel > Four ways to enable created_at in Laravel ORM

Four ways to enable created_at in Laravel ORM

Release: 2021-08-19 09:00:45
forward
2846 people have browsed it

The following is the Laravel framework tutorial column to introduce you to several methods of opening only created_at in Laravel ORM. I hope it will be helpful to friends in need!

Method 1:

class User extends Model {
  public $timestamps = false;//关闭自动维护
  public static function boot() {
    parent::boot();
    #只添加created_at不添加updated_at
    static::creating(function ($model) {
      $model->created_at = $model->freshTimestamp();
      //$model->updated_at = $model->freshTimeStamp();
    });
  }
}
Copy after login

There is a pitfall here: the value of created returned when using the create method to create a record is like this:

“created_at”: {
“date”: “2020-09-27 13:47:12.000000”,
“timezone_type”: 3,
“timezone”: “Asia/Shanghai”
},
Copy after login

Not as imagined

“created_at”: “2020-09-27 13:49:39”,
Copy after login

Method 2:

class User extends Model {
  const UPDATED_AT = null;//设置update_at为null
  //const CREATED_AT = null;
}
Copy after login

There is a pitfall here: using destroy to delete will report an error

Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute()
Copy after login

Using delete will not affect , wherein does not affect

Method 3:

class User extends Model {
  //重写setUpdatedAt方法
  public function setUpdatedAt($value) {
    // Do nothing.
  }
  //public function setCreatedAt($value)
  //{
    // Do nothing.
  //}
}
Copy after login

Method 4:

class User extends Model {
  //重写setUpdatedAt方法
  public function setUpdatedAtAttribute($value) {
    // Do nothing.
  }
  //public function setCreatedAtAttribute($value)
  //{
    // Do nothing.
  //}
}
Copy after login

can also be set in Migration ( I haven’t tried it specifically, I saw it in other articles)

class CreatePostsTable extends Migration {
  public function up() {
   Schema::create('posts', function(Blueprint $table) {
   $table->timestamp('created_at')
   ->default(DB::raw('CURRENT_TIMESTAMP'));
  });
}
Copy after login

Related recommendations: The latest five Laravel video tutorials

The above is the detailed content of Four ways to enable created_at in Laravel ORM. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:杨子
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template