版本 | 功能调整 |
---|---|
5.0.8 | 中间表名无需前缀,并支持定义中间表模型 |
5.0.6 | attach 方法返回值改为Pivot 对象 |
例如,我们的用户和角色就是一种多对多的关系,我们在User模型定义如下:
<?phpnamespace appindexmodel;use thinkModel;class User extends Model { public function roles() { return $this->belongsToMany('Role'); } }
belongsToMany方法的参数如下:
belongsToMany('关联模型名','中间表名','外键名','当前模型关联键名',['模型别名定义']);
5.0.8+
版本开始,中间表名无需添加表前缀,并支持定义中间表模型,例如:
public function roles() { return $this->belongsToMany('Role','ppindexmodelAccess'); }
我们可以通过下面的方式获取关联数据
$user = User::get(1);// 获取用户的所有角色 dump($user->roles);
如果要获取中间表数据,可以使用
$user = User::get(1); $roles = $user->roles;foreach($roles as $role){ // 获取中间表数据 dump($role->pivot); }
$user = User::get(1);// 增加关联数据 会自动写入中间表数据$user->roles()->save(['name'=>'管理员']);// 批量增加关联数据$user->roles()->saveAll([ ['name'=>'管理员'], ['name'=>'操作员'], ]);
只新增中间表数据,可以使用
$user = User::get(1);// 仅增加关联的中间表数据$user->roles()->save(1);// 或者$role = Role::get(1);$user->roles()->save($role);// 批量增加关联数据$user->roles()->saveAll([1,2,3]);
单独更新中间表数据,可以使用:
$user = User::get(1);// 增加关联的中间表数据$user->roles()->attach(1);// 传入中间表的额外属性$user->roles()->attach(1,['remark'=>'test']);// 删除中间表数据$user->roles()->detach([1,2,3]);
V5.0.6+
版本开始,attach
方法的返回值是一个Pivot
对象实例,如果是附加多个关联数据,则返回Pivot
对象实例的数组。
我们可以在Role
模型中定义一个相对的关联关系,例如:
<?phpnamespace appindexmodel;use thinkModel;class Role extends Model { public function users() { return $this->belongsToMany('User'); } }