下面由Laravel框架教程欄目給大家介紹Laravel ORM只開(kāi)啟created_at的幾種方法,希望對(duì)需要的朋友有所幫助!
方法一:
class User extends Model { public $timestamps = false;//關(guān)閉自動(dòng)維護(hù) public static function boot() { parent::boot(); #只添加created_at不添加updated_at static::creating(function ($model) { $model->created_at = $model->freshTimestamp(); //$model->updated_at = $model->freshTimeStamp(); }); } }
此處有坑:使用create方法創(chuàng)建一條記錄時(shí)返回值的created的值是這樣的:
“created_at”: { “date”: “2020-09-27 13:47:12.000000”, “timezone_type”: 3, “timezone”: “Asia/Shanghai” },
并不是想象中的
“created_at”: “2020-09-27 13:49:39”,
方法二:
class User extends Model { const UPDATED_AT = null;//設(shè)置update_at為null //const CREATED_AT = null; }
此處有坑:使用destroy刪除會(huì)報(bào)錯(cuò)
Missing argument 2 for IlluminateDatabaseEloquentModel::setAttribute()
使用delete不影響,wherein也不影響
方法三:
class User extends Model { //重寫(xiě)setUpdatedAt方法 public function setUpdatedAt($value) { // Do nothing. } //public function setCreatedAt($value) //{ // Do nothing. //} }
方法四:
class User extends Model { //重寫(xiě)setUpdatedAt方法 public function setUpdatedAtAttribute($value) { // Do nothing. } //public function setCreatedAtAttribute($value) //{ // Do nothing. //} }
在Migration中也可以設(shè)置(具體沒(méi)試過(guò),在別的文章里看見(jiàn)的)
class CreatePostsTable extends Migration { public function up() { Schema::create('posts', function(Blueprint $table) { $table->timestamp('created_at') ->default(DB::raw('CURRENT_TIMESTAMP')); }); }