Home>Article>PHP Framework> [Organization and sharing] 8 tips for using Laravel model timestamps

[Organization and sharing] 8 tips for using Laravel model timestamps

青灯夜游
青灯夜游 forward
2022-09-22 20:18:59 1574browse

Below, the Laravel Tutorial column will share with you 8 tips on how to use Laravel model timestamps. See if you have never used them. If not, come and collect them. I hope it will be helpful to everyone!

[Organization and sharing] 8 tips for using Laravel model timestamps

By default, theLaravel Eloquentmodel default data tables includecreated_atandupdated_atTwo fields. Of course, we can make a lot of custom configurations and implement many interesting functions. Here are some examples.


1. Disable timestamp

If the data table does not have these two fields, when saving the dataModel::create($arrayOfValues);——You will seeSQL error.LaravelWhen automatically fillingcreated_at / updated_at, these two fields cannot be found.

Disable automatic filling of timestamps, just add the previous attribute inEloquent Model:

class Role extends Model { public $timestamps = FALSE; // ... 其他的属性和方法 }

2. Modify the default list of timestamps

What if you are currently using a non-Laraveltype of database, that is, your timestamp column is named differently? Perhaps, they are calledcreate_timeandupdate_timerespectively. Congratulations, you can also define it like this in the model:

class Role extends Model { const CREATED_AT = 'create_time'; const UPDATED_AT = 'update_time';

3. Modify the timestamp date/time format

The following content refers to the official Laravel documentation :

By default, the timestamp is automatically formatted as'Y-m-d H:i:s'. If you need to customize the timestamp format, you can set the$dateFormatproperty in your model. This property determines the format in which the date is stored in the database and when serialized into an array or JSON:

class Flight extends Model { /** * 日期时间的存储格式 * * @var string */ protected $dateFormat = 'U'; }

4. Many-to-many: Intermediate table with timestamp

When in a many-to-many association, the timestamp will not be automatically filled in, such as the intermediate tablerole_user# of the user tableusersand the role tableroles##.

In this model you can define the relationship like this:

class User extends Model { public function roles() { return $this->belongsToMany(Role::class); } }
Then when you want to add a role to the user, you can use it like this:

$roleID = 1; $user->roles()->attach($roleID);
By default, this middle Table

does not contain timestamp. AndLaravelwill not try to automatically populatecreated_at/updated_at

but if you want to automatically save the timestamp, you need to add

created_at/updated_at in the migration file, and then add->withTimestamps();

public function roles() { return $this->belongsToMany(Role::class)->withTimestamps(); }

5. Uselatest()Andoldest()Perform timestamp sorting

There are two "shortcut methods" for using timestamp sorting.

Instead:

User::orderBy('created_at', 'desc')->get();
This is faster:

User::latest()->get();
By default,

latest()usescreated_atsorting.

Correspondingly, there is an

oldest(), which will be sorted like thiscreated_at ascending

User::oldest()->get();
Of course, you can also use other specified fields Sort. For example, if you want to use

updated_at, you can do this:

$lastUpdatedUser = User::latest('updated_at')->first();

6. Do not trigger the modification ofupdated_at

Whenever an

Eloquentrecord is modified, the current timestamp will be automatically used to maintain theupdated_atfield, which is a great feature.

But sometimes you don’t want to do this. For example: when adding a certain value, you think this is not a “whole row update”.

Then you can do the same as above - just disable

timestampsand remember this is temporary:

$user = User::find(1); $user->profile_views_count = 123; $user->timestamps = false; $user->save();

7. Update times only Stamps and associated timestamps

Just the opposite of the previous example, maybe you need to update only the

updated_atfield without changing the other columns.

So, the following writing method is not recommended:

$user->update(['updated_at' => now()]);
You can use a faster method:

$user->touch();
Another situation, sometimes you not only want to update the current model The

updated_atalso hopes to update the record of the superior relationship.

For example, if a

commentis updated, then you want to update theupdated_atof theposttable.

Then, you need to define the

$touchesattribute in the model:

class Comment extends Model { protected $touches = ['post']; public function post() { return $this->belongsTo('Post'); } }

8. Timestamp field automatic conversionCarbonClass

One last tip, but more like a reminder since you should already know it.

By default, the

created_atandupdated_atfields are automatically converted to$dates,so you don’t need to convert them to
Carboninstance, that is, the method ofCarboncan be used.

For example:

$user->created_at->addDays(3); now()->diffInDays($user->updated_at);

That’s it, a quick but hopefully helpful tip!

English original address: https://laraveldaily.com/8-tricks-with-laravel-timestamps/

Translation address: https://learnku.com/laravel/ t/39353

The above is the detailed content of [Organization and sharing] 8 tips for using Laravel model timestamps. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:learnku.com. If there is any infringement, please contact admin@php.cn delete