指尖上的记忆指尖上的记忆
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub
首页
  • 基础
  • Laravel框架
  • Symfony框架
  • 基础
  • Gin框架
  • 基础
  • Spring框架
  • 命令
  • Nginx
  • Ai
  • Deploy
  • Docker
  • K8s
  • Micro
  • RabbitMQ
  • Mysql
  • PostgreSsql
  • Redis
  • MongoDb
  • Html
  • Js
  • 前端
  • 后端
  • Git
  • 知识扫盲
  • Golang
🌟 gitHub

larave模型中的几个小技巧:

①模型中关于 $dates 和 $dateFormat

//将 [] 中自定的字段,转为 Carbon 类的时间对象,可以使用 Carbon 的方法,比如:$data->deleted_at->getTimestamp();默认 created_at 和 updated_at 都已经转过了,就不用在 [] 里 写了 protected $dates = ['deleted_at'];

//定义时间存储到数据的格式,默认 'Y-m-d H:i:s' protected $dateFormat = 'Y-m-d H:i';

②模型中关于scope的使用,主要有两种使用方式:


//局部使用Scope,这个status scope 还带了参数,更加灵活, 使用的时候直接 Produt::query()->->status(1)->get();就可以了
public function scopeStatus($query, $status = 0)
{
      return $query->where('status', $status);
}

//全局使用Scope,这个不许用显示的调用
protected static function boot()
{
    parent::boot();

    //通过给scope 定义一个名称 filter,定义名称的好处是,可以通过 withoutGlobalScope(),取消指定名称的 scope;或者 withoutGlobalScopes(),不带参数可以取消所有scope
    static::addGlobalScope('filter', function (Builder $builder) {
        $builder->where('status', 0);
    });

    //匿名 scope
    static::addGlobalScope(function (Builder $builder) {
        $builder->where('status', 0);
    });

    //定义一个 Scope 实例,一定要new 一个对象
    static::addGlobalScope(new StatusScope());
 }


 //StatusScope 类如下,实现了Scope的一个apply接口
 <?php

 /**
  * Created by PhpStorm.
  * User: guoshipeng
  * Date: 2022/9/23
  * Time: 11:26
  */

 namespace App\Scopes;

 use Illuminate\Database\Eloquent\Builder;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Scope;

 class StatusScope implements Scope
 {
     public function apply(Builder $builder, Model $model)
     {
         return $builder->where('status', 1);

     }
 }

 ③自动维 护创建时间 或 更新时间
 直接在模型里面加 public    $timestamps = true; 即可实现自动维护<br>
 有时候我们只想维护其中一个,怎么弄,比如不需要自动更新时间,可以在模型里加: const UPDATED_AT = null;<br>
 或者我们不想要 updated_at,想要改为其它的,我们可以在模型里加:const UPDATED_AT = 'update_time';