代码之家  ›  专栏  ›  技术社区  ›  Prafulla Kumar Sahu umang naik

拉威尔雄辩模型关系

  •  0
  • Prafulla Kumar Sahu umang naik  · 技术社区  · 6 年前

    我的应用程序基于

    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);
        } 
    }
    

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

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

    3 回复  |  直到 6 年前
        1
  •  1
  •   Javi Mollá    6 年前

    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');
        }
    }
    

    这样的话,你就不必问对方的关系了

        2
  •  0
  •   Carlos Salazar    6 年前

    这个错误说,问题要么在你的关系建立的方式上,要么在你的表中

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

    role_id ,当你建立一段像

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

    tablename_id 在您要传递的模型中,如果您想通过第三个表获得它们,您可以使用 belongsToMany 在你的 permission 模型或使用 polymorphic relationships