17 模型的定义

模型变量的含义

  1. class Navigation extends Model
  2. {
  3. protected $table = 'navigations';
  4. /**
  5. * 主键
  6. * @var string
  7. */
  8. protected $primaryKey = 'id';
  9. /**
  10. * 主键是否为自增类型
  11. * @var bool
  12. */
  13. public $incrementing = true;
  14. /**
  15. * 主键类型
  16. * @var string
  17. */
  18. protected $keyType = 'int';
  19. /**
  20. * 是否使用默认的created_at和updated_at时间戳列
  21. * @var bool
  22. */
  23. public $timestamps = true;
  24. /**
  25. * 自定义时间格式, 默认读取config/app.php文件中的timezone值
  26. * @var string
  27. */
  28. protected $dateFormat = 'PRC';
  29. /**
  30. * 设置默认系统接管的时间戳列
  31. */
  32. const CREATED_AT = 'created_at';
  33. const UPDATED_AT = 'updated_at';
  34. /**
  35. * 设置数据库连接, 默认读取config/database.php配置的数据库连接
  36. * @var string
  37. */
  38. protected $connection = 'mysql';
  39. /**
  40. * 许可批量操作字段, * 标识所有
  41. * @var array
  42. */
  43. protected $fillable = [];
  44. /**
  45. * 不允许批量操作字段, * 标识所有
  46. * @var array
  47. */
  48. protected $guarded = ['*'];
  49. }

模型可用的方法ide代码提示

  1. $ composer require barryvdh/laravel-ide-helper
  2. # 为Facades 生成注释
  3. $ php artisan ide-helper:generate
  4. # 为数据模型生成注释
  5. $ php artisan ide-helper:models
  6. # 生成PhpStorm Meta file
  7. $ php artisan ide-helper:meta

18 模型的增删改

创建

$user = new User;
$user->username = '张三';
$user->age = 5;
$user->save();


User::create([
    'username' => '张三',
  'age' => 5,
]);
// PS: 这个需要添加字段许可

修改

$user = User::find(2);
$user->username = '李四';
$user->save();

删除某一条记录

User::destory(1);
User::destory([1,2,3]);
// 返回成功执行行数

19 批量赋值和软删除

软删除

开启软删除
use Illuminate\Database\Eloquent\SoftDeletes;

class ImageType extends Model
{
    protected $table = 'image_type';

  // 开启软删除所需要引入的train类, 默认字段名为deleted_at
    use SoftDeletes;
}

使用软删除
// 引入SoftDeletes后所有的删除操作都会变成deleted_at的值为删除的时间
ImageType::destory(1);

// 软删除后所有基础查看都是无法查询到被软删除后的数据
// 可以通过withTrashed()来查找带有被软删除后的数据
ImageType::withTrashed()->get();

// 先要值查询被软删除的数据
ImageType::onlyTrashed()->get();

// 判断某一条记录否是被软删除
ImageType::withTrashed()->find(1)->trashed();
// PS: 若被真实删除了会直接报没有trashed()方法的错

// 恢复被软删除的数据
ImageType::withTrashed()->find(1)->restore();

// 真实删除
ImageType::onlyTrashed()->where('id', '>', 2)
  ->forceDelete()
// PS: 若没有指定某条记录最好通过onlyTrashed()去获取所有被软删除的数据
//     不然容易导致删除掉未被软删除的数据

20 模型的作用域(自定义查询)

模型的作用域实际上就是对模型查询的一个封装

本地作用域

// 封装find_in_set表达式
public function scopeFindInSet($query, $column,  $value)
{
    return $query->whereRaw("find_in_set(?, `{$column}`)", $value);
}

// 调用的时候可以直接调用
ImageType::findInSet('title', [5,6]);


// PS: 这里需要注意的是数据库里边必须是1, 2, 3, 4, 5, 6

全局作用域

每一次查询的时候都会进行调用

首先创建一个全局使用的类
<?php

namespace App\Scopes;

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

class IdScope implements Scope
{
    public function apply(Builder $builder, Model $model)
    {
        return $builder->where('id', '>', 0);
    }
}

模型类中引入
<?php

namespace App\Models\Image;

use App\Models\Model;

class ImageType extends Model
{
    protected $table = 'image_type';

    // 启用全局作用域 laravel6.x 引入方式
    protected static $booted = [\App\Scopes\IdScope::class];

    // 启用全局作用域 laravel7.x 引入方式
    protected static function booted() {
          parent::booted();
        static::addFlobalScope(new \App\Scopes\IdScope);
    }

    // 启用全局作用域 laravel7.x 闭包引入方式
    protected static function booted() {
          parent::booted();
        static::addFlobalScope('id', function($builder) {
                $builder->where('id', '>', 0);
        });
    }
}

某次查询不需要使用全局的作用域
// 无设置别名
ImageType::withoutGlobalScope(\App\Scopes\IdScope::class)->get();

// 有设置别名
ImageType::withoutGlobalScope('id')->get();

// 取消多个
ImageType::withoutGlobalScope(['id'])->get();

21 模型的访问器和修改器

访问器

增加一个数据库中没有的字段

class User extends Model
{
    // 追加字段
    protected $appends = ['info'];

    // 追加字段访问器
    public function getInfoAttribute()
    {
        // 获取访问器修改后的数据做拼接
        return $this->username . '-' . $this->gender;

        // 获取访问器修改前的数据做拼接
        return $this->attribute['username'] . '-' . $this->attribute['gender'];
    }
}

转换器

class Order extends Model
{
    // 设置日期列
    protected $dates = ['pay_time'];

    // 属性转换列
    protected $casts = [
        'enable' => 'boolean'
    ];

}

22 集合的使用

$collection = collect(['张三', '李四', '王五', '刘六']);


// 获取回调函数中相反的结果
$collection->reject(function($value, $key) {
    return $value == '张三';
})->toArray();

// ['李四', '王五', '刘六']


// 查找相关的数据返回对应的key, 找不到返回false
$collection->search('王五');   // 2

// 分段显示(一维数组转二位数组)
$collection->chunk(2)->toArray; // 每两个分一组
/*
  [
    ['张三', '李四'],
    ['王五', '刘六']
  ]
*/


// 自定义集合方法
Collection::macro('toUpper', function(){

    // 这里会把调用的值传过来
  return $this->map(function($value) {
      return strtoupper($value);
  });

});

23 集合的常用方法(暂时掠过)

$collection = collect(['张三', '李四', '王五', '刘六']);

// 数组降维 二维转一维, 三维转二维, 转化方式合并数组内部所有元素
// 类似于 array_reduce($array, 'array_merge', []);
$collection->collapse()->all();


// 统计数组中每个数据有多少个重复数据
// 当$function不为null的时候
$collection->countBy($function = null)

24 模型的数据集合

集合中的所有的方法都是可以使用的

$user = User::get();

// 判断集合中是否有指定的模型, 默认是查找id的
$user->contains(2);
$user->contains(User::find(2));
$user->contains('title', '=', 0);

// 获取数据, 查找参数是id, 找不到则返回默认值
$user->find(2);
$user->find(144, '默认值');

// 返回所有id(主键)
$user->modelKeys();

//返回给定主键以外的所有模型
$user->except([19, 20, 21]);

//返回给定主键的所有模型
$user->only([19, 20, 21]);

//返回模型中的唯一模型
$user->unique();

25 模型的一对一关联

参数: 第一个为命名空间, 第二个为外键, 第三个为主键

26 模型的一对多关联

// 关联后再筛选
User::find(12)->profile()->where('name', '张三');

27 模型的多对多关联(未掌握)

参数: 第一个为命名空间, 第二个中间表, 第三个为本表主键, 第四个为外表主键

默认设置 中间表是需要将两张表名都写起来。
例: 权限表为 role 用户表为user 那么他们的中间表默认为 role_user

// 返回的实际上是role_user表的模型
User::find(12)->role();

image.png