Laravel eloquent 模型关系

Laravel eloquent model relationship

我的应用基于

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()

的错误

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

按照您定义关系的方式,您必须明确要求检索该关系:

App\User::with('Roles')->find(1)->roles()

在文档中,用户和角色的关系是这样的:

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

class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }
}

这样,你就不用问关系了

我想我找到了 .if you have properly defined relations through hasMany and belongsTo in your models, but haven't provided foreign key in the table of the model who belongsTo other table, your relations won't work. In documentation too, it suggests to use foreign_key to use One-to-Many 关系问题的答案。

Entrust 数据库设计基于多对多关系。这样用户就可以拥有多个 roles.Purly,如 Laravel documentation.

中所述

问题要么出在你们建立关系的方式上,要么出在你们 table 上,错误提示

 Unknown column 'users.role_id' in 'where clause'

这意味着在您的用户 table 中缺少列 role_id,当您建立

这样的关系时
public function users()
{
    return $this->hasMany(User::class);
}

hasMany 将尝试在您传递的模型中找到 tablename_id,如果您想通过三分之一 table 获得它们,您可以在 belongsToMany 上使用 permission 模型或使用 polymorphic relationships