laravel 模型关联真的头疼

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

《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 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年前

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