laravel ORM開啟created_at步驟總結

來源:互聯網
上載者:User
這次給大家帶來laravel ORM開啟created_at步驟總結,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”: “2017-09-27 13:47:12.000000”, “timezone_type”: 3, “timezone”: “Asia/Shanghai” }, 並不是想象中的 “created_at”: “2017-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.  //}}

ps:

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

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

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

PHP運用foreach轉換數組步驟詳解

php雙引號中訪問數組元素報錯如何處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.