牛骨文教育服务平台(让学习变的简单)

多对多关联

多对多关联

版本功能调整
5.0.8中间表名无需前缀,并支持定义中间表模型
5.0.6attach方法返回值改为Pivot对象

关联定义

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

namespace 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","appindexmodelAccess");
    }

关联查询

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

$user = User::get(1);
// 获取用户的所有角色
dump($user->roles);

如果要获取中间表数据,可以使用

$user = User::get(1);
// 获取中间表数据
dump($user->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模型中定义一个相对的关联关系,例如:

namespace appindexmodel;

use thinkModel;

class Role extends Model 
{
    public function users()
    {
        return $this->belongsToMany("User");
    }
}