How to only use created_at in Laravel

2020-02-07 16:54发布

I want only use created_at , how to do it?

I know:

This can custom timestamps name

const CREATED_AT = 'created';
const UPDATED_AT = 'updated';

This can disable timestamps

public $timestamps = false;

标签: php laravel
17条回答
爷、活的狠高调
2楼-- · 2020-02-07 17:11

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.

查看更多
Juvenile、少年°
3楼-- · 2020-02-07 17:14

My solution for this is using a new __construct method.

See:

class MyModel extends Eloquent {

    public $timestamps = false;

    public function __construct(array $attributes = [])
    {
            parent::__construct($attributes);

            $this->attributes['created_at'] = $this->freshTimestamp();
    }
}
查看更多
三岁会撩人
4楼-- · 2020-02-07 17:15

I solved by adding default value CURRENT_TIMESTAMP in my database for the column created_at. And In my model I use this below code

public $timestamps = false;
protected $dates = ['created_at'];

I hope this method works in all versions of laravel.

查看更多
对你真心纯属浪费
5楼-- · 2020-02-07 17:15

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

public $timestamps = false;

in your model.

查看更多
小情绪 Triste *
6楼-- · 2020-02-07 17:16

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.`

查看更多
甜甜的少女心
7楼-- · 2020-02-07 17:16

Use on the top the class:

const UPDATED_AT = null;

or

const CREATED_AT = null;

查看更多
登录 后发表回答