首頁  >  文章  >  php框架  >  四種Laravel ORM開啟created_at的方法

四種Laravel ORM開啟created_at的方法

藏色散人
藏色散人轉載
2021-08-18 11:46:072758瀏覽

以下由Laravel框架教學專欄為大家介紹Laravel ORM只開啟created_at的幾種方法,希望對需要的朋友有幫助!

方法一:

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();
    });
  }
}

這裡有坑:使用create方法建立一筆記錄時傳回值的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;//设置update_at为null
  //const CREATED_AT = null;
}

此處有坑:使用destroy刪除會報錯

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

使用delete不影響,wherein也不影響

方法三:

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

方法四:

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

在Migration中也可以設定(具體沒試過,在別的文章裡看見的)

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

相關推薦:最新的五個Laravel影片教學

#

以上是四種Laravel ORM開啟created_at的方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:杨子。如有侵權,請聯絡admin@php.cn刪除