Laravel eloquent 模型关系

普拉富拉·库马尔·萨胡

我的应用程序建立在

Laravel: 5.6.35
PHP 7.2.4
Entrust: 1.9

我的榜样

class Role extends EntrustRole
{
    public function permissions()
    {
        return $this->belongsToMany(Permission::class);
    }

    public function users()
    {
        return $this->hasMany(User::class);
    }
}

我的用户模型是

class User extends Authenticatable
{
    public function role()
    {
        return $this->belongsTo(Role::class);
    } 
}

现在你可以在 Tinker 中注意到

D:\work\www\myapp>php artisan tinker
Psy Shell v0.9.7 (PHP 7.2.4 — cli) by Justin Hileman
>>> App\models\Role::find(1)->users()->get()
Illuminate/Database/QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.role_id' in 'where clause' (SQL: select * from `users` where `users`.`role_id` = 1 and `users`.`role_id` is not null)'
>>> App\User::find(1)->role()->get();
=> Illuminate\Database\Eloquent\Collection {#2937
     all: [],
   }
>>> App\User::find(1)->roles()->get();
=> Illuminate\Database\Eloquent\Collection {#2941
     all: [
       App\models\Role {#2930
         id: 1,
         name: "super-admin",
         display_name: "Super Admin",
         description: "This will be one permission, that can not be assigned or modified.",
         created_at: "2018-09-07 12:11:35",
         updated_at: "2018-09-07 12:11:35",
         pivot: Illuminate\Database\Eloquent\Relations\Pivot {#2927
           user_id: 1,
           role_id: 1,
         },
       },
     ],
   }

我得到了 的结果App\User::find(1)->roles(),但我的用户模型有函数role(),空集合App\User::find(1)->role()和错误App\models\Role::find(1)->users()

所以请给出一些想法,如何解决这个问题?

普拉富拉·库马尔·萨胡

我想我在这里找到了我的问题的答案。如果您在模型中通过 hasMany 和belongsTo 正确定义了关系,但没有在模型的表中提供外键谁属于其他表,则您的关系将不起作用。在文档中,它也建议使用 foreign_key 来使用一对多关系。

Entrust 数据库设计基于多对多关系。这样用户就可以拥有多个角色。如 Laravel文档中所述

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章