加载中...

多对多关联


多对多关联

关联定义

例如,我们的用户和角色就是一种多对多的关系,我们在User模型定义如下:

  1. <?php
  2. namespace app\index\model;
  3. use think\Model;
  4. class User extends Model
  5. {
  6. public function roles()
  7. {
  8. return $this->belongsToMany('Role');
  9. }
  10. }

belongsToMany方法的参数如下:

belongsToMany('关联模型','中间表','外键','关联键');

  • 关联模型(必须):模型名或者模型类名
  • 中间表:默认规则是当前模型名+_+关联模型名 (可以指定模型名)
  • 外键:中间表的当前模型外键,默认的外键名规则是关联模型名+_id
  • 关联键:中间表的当前模型关联键名,默认规则是当前模型名+_id

中间表名无需添加表前缀,并支持定义中间表模型,例如:

  1. public function roles()
  2. {
  3. return $this->belongsToMany('Role','\\app\\model\\Access');
  4. }

中间表模型类必须继承think\model\Pivot,例如:

  1. <?php
  2. namespace app\index\model\Access;
  3. use think\model\Pivot;
  4. class Access extends Pivot
  5. {
  6. protected $autoWriteTimestamp = true;
  7. }

中间表模型的基类Pivot默认关闭了时间戳自动写入,上面的中间表模型则开启了时间戳字段自动写入。

关联查询

我们可以通过下面的方式获取关联数据

  1. $user = User::get(1);
  2. // 获取用户的所有角色
  3. $roles = $user->roles;
  4. foreach ($roles as $role) {
  5. // 输出用户的角色名
  6. echo $role->name;
  7. // 获取中间表模型
  8. dump($role->pivot);
  9. }

关联新增

  1. $user = User::get(1);
  2. // 给用户增加管理员权限 会自动写入角色表和中间表数据
  3. $user->roles()->save(['name'=>'管理员']);
  4. // 批量授权
  5. $user->roles()->saveAll([
  6. ['name'=>'管理员'],
  7. ['name'=>'操作员'],
  8. ]);

只新增中间表数据(角色已经提前创建完成),可以使用

  1. $user = User::get(1);
  2. // 仅增加管理员权限(假设管理员的角色ID是1)
  3. $user->roles()->save(1);
  4. // 或者
  5. $role = Role::get(1);
  6. $user->roles()->save($role);
  7. // 批量增加关联数据
  8. $user->roles()->saveAll([1,2,3]);

单独更新中间表数据,可以使用:

  1. $user = User::get(1);
  2. // 增加关联的中间表数据
  3. $user->roles()->attach(1);
  4. // 传入中间表的额外属性
  5. $user->roles()->attach(1,['remark'=>'test']);
  6. // 删除中间表数据
  7. $user->roles()->detach([1,2,3]);

attach方法的返回值是一个Pivot对象实例,如果是附加多个关联数据,则返回Pivot对象实例的数组。

定义相对的关联

我们可以在Role模型中定义一个相对的关联关系,例如:

  1. <?php
  2. namespace app\index\model;
  3. use think\Model;
  4. class Role extends Model
  5. {
  6. public function users()
  7. {
  8. return $this->belongsToMany('User');
  9. }
  10. }

还没有评论.