Home > Article > PHP Framework > Four ways to enable created_at in Laravel ORM
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();
});
}
}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”
},Not as imagined
“created_at”: “2020-09-27 13:49:39”,
Method 2:
class User extends Model {
const UPDATED_AT = null;//设置update_at为null
//const CREATED_AT = null;
}There is a pitfall here: using destroy to delete will report an error
Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute()
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.
//}
}Method 4:
class User extends Model {
//重写setUpdatedAt方法
public function setUpdatedAtAttribute($value) {
// Do nothing.
}
//public function setCreatedAtAttribute($value)
//{
// Do nothing.
//}
}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'));
});
}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!