标签:php 5.0 rgb nsf lock pac name 功能 更新
| 版本 | 功能调整 | 
|---|---|
| 5.0.8 | 中间表名无需前缀,并支持定义中间表模型 | 
| 5.0.6 | attach方法返回值改为Pivot对象 | 
例如,我们的用户和角色就是一种多对多的关系,我们在User模型定义如下:
namespace app\index\model;
use think\Model;
class User extends Model 
{
    public function roles()
    {
        return $this->belongsToMany(‘Role‘);
    }
}belongsToMany方法的参数如下:
belongsToMany(‘关联模型名‘,‘中间表名‘,‘外键名‘,‘当前模型关联键名‘,[‘模型别名定义‘]);
5.0.8+版本开始,中间表名无需添加表前缀,并支持定义中间表模型,例如:
    public function roles()
    {
        return $this->belongsToMany(‘Role‘,‘\\app\\model\\Access‘);
    }我们可以通过下面的方式获取关联数据
$user = User::get(1);
// 获取用户的所有角色
dump($user->roles);$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模型中定义一个相对的关联关系,例如:
namespace app\index\model;
use think\Model;
class Role extends Model 
{
    public function users()
    {
        return $this->belongsToMany(‘User‘);
    }
}标签:php 5.0 rgb nsf lock pac name 功能 更新
原文地址:http://www.cnblogs.com/q1104460935/p/6916182.html