laravel 模型关联真的头疼

先定义三个表 user role user_role
现在多对多,文档都是 user->user_role->role 或者
role->user_role->role,
如果我现在定义一个user_role 模型,怎么关联可以从 user_role 查询到 user,role 的信息????

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
最佳答案

我使用多对多时,一般不会给定义中间模型,因为多对多的中间表本身就是做中间作用的

当然如果有这种需求可以这样

class UserRole extends Model
{
    public function user()
    {
        return $this->belongTo(User::class, 'user_id');
    }

    public function role()
    {
        return $this->belongTo(Role::class, 'role_id');
    }
}

不明白需要那几种查询,索性就列出一些我认为可能用到的

会用到一个知识点,《预加载》

// 查询所有 (结果中就会些有 user role 的数据了)
UserRole::with(['user', 'role'])->get();

// 查询相关ID
UserRole::with(['user'])->where('user_id', 1)->get();
UserRole::with(['role'])->where('role_id', 1)->get();
UserRole::with(['user', 'role'])->where('user_id', 1)->where('role_id', 1)->get();

希望能帮到你

3年前 评论
sunny123456 (楼主) 3年前
讨论数量: 5

user_roleuserrole的中间表,每条记录都有user_idrole_id,为什么要给中间表建模型?

3年前 评论
sunny123456 (楼主) 3年前

有点没听懂你是目的。 1.中间表可以有多余的字段,pivot属性获取 2.我不太定义中间表模型,如果定义了中间表模型,应该等于和role、user两方都是一对多的。你尝试定义获取看看

3年前 评论
sunny123456 (楼主) 3年前

同问,搞不懂如何使用模型关联多表查询,DB真香 :joy:

AdminRoleMenu::with(['adminRoles' => function($query) {
     $query->where('id', 1);
}])->get()->toArray();

adminRolesAdminRoleMenu模型中关联方法

public function adminRoles()
{
    return $this->hasOne('App\Models\AdminRoles', 'id', 'role_id');
}
3年前 评论
sunny123456 (楼主) 3年前

user_role 模型里面写 user() 和 role() 都是 belongto

3年前 评论
sunny123456 (楼主) 3年前

我使用多对多时,一般不会给定义中间模型,因为多对多的中间表本身就是做中间作用的

当然如果有这种需求可以这样

class UserRole extends Model
{
    public function user()
    {
        return $this->belongTo(User::class, 'user_id');
    }

    public function role()
    {
        return $this->belongTo(Role::class, 'role_id');
    }
}

不明白需要那几种查询,索性就列出一些我认为可能用到的

会用到一个知识点,《预加载》

// 查询所有 (结果中就会些有 user role 的数据了)
UserRole::with(['user', 'role'])->get();

// 查询相关ID
UserRole::with(['user'])->where('user_id', 1)->get();
UserRole::with(['role'])->where('role_id', 1)->get();
UserRole::with(['user', 'role'])->where('user_id', 1)->where('role_id', 1)->get();

希望能帮到你

3年前 评论
sunny123456 (楼主) 3年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!