Home  >  Article  >  PHP Framework  >  8 Laravel model timestamp usage tips that you deserve to know (Collection)

8 Laravel model timestamp usage tips that you deserve to know (Collection)

青灯夜游
青灯夜游forward
2021-12-20 16:43:362677browse

The following tutorial column of Laravel will share with you 8 tips on how to use Laravel model timestamps. See if you haven’t used them before. If not, come and collect them now. I hope Helpful for everyone!

8 Laravel model timestamp usage tips that you deserve to know (Collection)

By default, the Laravel Eloquent model default data table has two fields: created_at and updated_at. Of course, we can make a lot of custom configurations and implement many interesting functions. Below are examples.

1. Disable timestamp

If the data table does not have these two fields, Model::create($arrayOfValues); when saving the data - you will see SQL error. Laravel cannot find these two fields when automatically filling created_at / updated_at.

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

class Role extends Model
{
  public $timestamps = FALSE;

  // ... 其他的属性和方法
}

2. Modify the default list of timestamps

If the current What should I do if I am using a non-Laravel database and my timestamp column is named differently? Perhaps, they are called create_time and update_time respectively. 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 a custom timestamp format, you can set the $dateFormat property in your model. This attribute determines the storage format of the date in the database, and the format 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 table role_user between the user table users and the role table roles.

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 The table does not contain timestamps. And Laravel will not try to automatically fill in created_at/updated_at
But if you want to automatically save timestamps, you need to add created_at/updated_at in the migration file, and then add ->withTimestamps();## in the association of the model #

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

5. Use latest() and oldest() for timestamp sorting

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

Instead:

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

It’s faster to do this:

User::latest()->get();

By default, latest() uses created_at sorting.

Correspondingly, there is an oldest(), which will sort created_at ascending

User::oldest()->get();

Of course, you can also sort by other specified fields. 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 of updated_at

Whenever, when the Eloquent record is modified, it will Automatically maintain the updated_at field using the current timestamp, 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 everything as above - just disable timestamps, remember this is temporary:

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

7. Only update timestamps and associated timestamps

Contrary to the previous example, maybe you need to update only the updated_at field without changing other columns.

Therefore, the following writing method is not recommended:

$user->update(['updated_at' => now()]);

You can use a faster method:

$user->touch();

Another situation, sometimes you want to not only update the current The updated_at of the model also hopes to update the records of the superior relationship.

For example, if a comment is updated, then you want to update the updated_at of the post table.

Then, you need to define the $touches attribute in the model:

class Comment extends Model {

  protected $touches = ['post'];

  public function post()
  {
    return $this->belongsTo('Post');
  }

}

8. The timestamp field is automatically converted to the Carbon class

The last tip, But more like a reminder because you should already know it.

By default, the created_at and updated_at fields are automatically converted to $dates,

so you don't need to convert them to Carbon instances to use Carbon's methods.

For example:

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

For more programming-related knowledge, please visit:

Programming Video! !

The above is the detailed content of 8 Laravel model timestamp usage tips that you deserve to know (Collection). For more information, please follow other related articles on the PHP Chinese website!

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