Summary of several methods for laravel ORM to turn on created_at only

  • 2021-09-04 23:50:31
  • OfStack

Method 1:


class User extends Model {
  public $timestamps = false;// Turn off automatic maintenance 
  public static function boot() {
    parent::boot();
    # Add only created_at Do not add updated_at
    static::creating(function ($model) {
      $model->created_at = $model->freshTimestamp();
      //$model->updated_at = $model->freshTimeStamp();
    });
  }
}

 There are pits here : Use create Method to create 1 Object that returns the value when a record is recorded created The value of is like this:  
 " created_at " : { 
 " date " :  " 2017-09-27 13:47:12.000000 " , 
 " timezone_type " : 3, 
 " timezone " :  " Asia/Shanghai "  
}, 
 It's not imagined  
 " created_at " :  " 2017-09-27 13:49:39 " , 

Method 2:


class User extends Model {
  const UPDATED_AT = null;// Settings update_at For null
  //const CREATED_AT = null;
}

 There are pits here : Use destroy Error will be reported when deleted  
Missing argument 2 for Illuminate\Database\Eloquent\Model::setAttribute() 
 Use delete Do not affect ,wherein Nor does it affect 

Method 3:


class User extends Model {
  // Rewrite setUpdatedAt Method 
  public function setUpdatedAt($value) {
    // Do nothing.
  }
  //public function setCreatedAt($value)
  //{
    // Do nothing.
  //}
}

Method 4:


class User extends Model {
  // Rewrite setUpdatedAt Method 
  public function setUpdatedAtAttribute($value) {
    // Do nothing.
  }
  //public function setCreatedAtAttribute($value)
  //{
    // Do nothing.
  //}
}

ps:

It can also be set in Migration (specifically not tried, seen 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 articles: