Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 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 Answer

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'];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...