How to only use created_at in Laravel

后端 未结 17 2058
自闭症患者
自闭症患者 2020-12-07 18:20

I want only use created_at , how to do it?

I know:

This can custom timestamps name

const CREATED_AT = \'created\';
const UPDATED_AT = \'updat         


        
相关标签:
17条回答
  • 2020-12-07 18:59

    Approach with only setUpdatedAt did not work with Laravel 5.1.7 because it has one more place where updated_at gets processed.

    Model class performUpdate method calls Builder class method:

    public function update(array $values)
    {
        return $this->query->update($this->addUpdatedAtColumn($values));
    }
    

    which leads us to

    return Arr::add($values, $column, $this->model->freshTimestampString());
    

    I'm not sure, why Laravel is processing updated_at twice - in performUpdate with $this->updateTimestamps() and then later in Builder with $this->addUpdatedAtColumn($values).

    With some debugging, I found that you have to also update your model with getUpdatedAtColumn override. At first I was afraid that it will try to update a non-existent field "null", but it turned out that Arr::add is smart enough to ignore null keys.

    So, in your model class add these:

    public function setUpdatedAt($value)
    {
        // Do nothing.
    }
    
    public function getUpdatedAtColumn()
    {
        return null;
    }
    

    This should be enough to disable both updates.

    0 讨论(0)
  • 2020-12-07 18:59

    Use on the top the class:

    const UPDATED_AT = null;

    or

    const CREATED_AT = null;

    0 讨论(0)
  • 2020-12-07 19:02

    On your model set

    const UPDATED_AT = null;

    or

    const CREATED_AT = null;

    it stops Laravel trying to update the updated_at/created_at field

    It works for Laravel 5.8

    And it is better than overwrite: setUpdatedAt in your model

    public function setUpdatedAt($value) : self 
    {
        // Do nothing.
        return $this;
    }
    

    because it is shorter and because the check for if (! is_null(static::UPDATED_AT) is happening in source code earlier than triggering setUpdatedAt

    0 讨论(0)
  • 2020-12-07 19:02

    You can use CURRENT_TIMESTAMP default value for created field in your MySQL table and set

    public $timestamps = false;
    

    in your model.

    0 讨论(0)
  • 2020-12-07 19:03

    I used very simple hack ;)

    class MyClass extends Model {

    const CREATED_AT = 'creation_date';
    const UPDATED_AT = 'creation_date';
    

    }

    I just pointed both to the same column :)

    0 讨论(0)
  • 2020-12-07 19:05

    In version 5.3 I just did public $timestamps = false; and then added protected $fillable = ['created_at']. Note: You can add anything you want, just make sure it matches the one in your table.`

    0 讨论(0)
提交回复
热议问题