Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

Laravel 7 - Timestamp field becomes ISODate

I have got a problem. When updating the model twice, the updatedAt field becomes from timestamp to ISODate. So after second loop updatedAt is changed to ISODate. Is there any explanation why does it work like this.

for($i = 0; $i < 2; $i++){
    $user = User::find('10');
    $user->mode = rand(1, 10);
    $user->save();
}

"updatedAt" : ISODate("2021-01-28T15:46:16.773Z"),
"createdAt" : 1611844860

Here is the User Model Class:

const CREATED_AT = 'createdAt';
const UPDATED_AT = 'updatedAt';

protected $casts = [
    'createdAt' => 'timestamp',
    'updatedAt' => 'timestamp',
];

public function setCreatedAtAttribute()
{
     $this->attributes['createdAt'] = time();
}

public function setUpdatedAtAttribute()
{
    $this->attributes['updatedAt'] = time();
}
question from:https://stackoverflow.com/questions/65940914/laravel-7-timestamp-field-becomes-isodate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try to not to use mutators, use protected $dateFormat & $dates instead of $casts nor mutators , e.g

protected $dateFormat = 'U';
protected $dates = ['createdAt', 'updatedAt'];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...