代码之家  ›  专栏  ›  技术社区  ›  Statharas.903

雄辩模型的关系不起作用;甚至连一个查询都没有

  •  2
  • Statharas.903  · 技术社区  · 8 年前

    我在子-父关系中有一个用户和一个角色模型,如下面的代码所示。结果是,我可以通过家长访问孩子,但反之亦然。访问子角色($user->role)只会给我ID。role列在roles表上有一个外键,但相反的不起作用。 大体上 $角色包含所有用户 $用户->角色不显示用户的角色,仅显示其id

    Laravel调试栏还显示,用户不执行额外的查询,而角色执行。

    用户表

    id name email password remember_token client role created_at updated_at

    角色表

    id name display_name description created_at updated_at

    用户模型

    namespace App;
    use Illuminate\Notifications\Notifiable;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Database\Eloquent\Model;
    use Laratrust\Traits\LaratrustUserTrait;
    use App\Client;
    use App\Role;
    use App\Permission;
    
    class User extends Authenticatable
    {
        use LaratrustUserTrait;
        use Notifiable;
    
        protected $fillable = [
            'name', 'email', 'password','role',
        ];
        public function client(){
            return $this->hasOne('App\Client', 'client');
        }
        public function role(){
            return $this->belongsTo('App\Role')->withDefault();
        }
    }
    

    角色模型

    namespace App;
    
    use Laratrust\Models\LaratrustRole;
    use App\Permission;
    use App\User;
    
    class Role extends LaratrustRole
    {
                protected $fillable = [
            'name', 'display_name', 'description',
        ];
            public function GetHasPermission($perm){
                return DB::table('permission_role')->where('role', $this->id)
                        ->where('permission',$perm)->first()->value('type');
            }
            public function users(){
                return $this->hasMany('App\User','role', 'id');
            }
            public function permissions(){
                return $this->hasMany('App\Permission');
            }
            public function getName(){
                return $this->name;
            }
    }
    

    编辑:应该注意,我使用的是Laratrust。

    1 回复  |  直到 8 年前
        1
  •  5
  •   Alexey Mezenin    8 年前

    因为你没有跟踪 Laravel naming conventions ,需要手动定义外键。因此,更改 role() 关系:

    public function role()
    {
        return $this->belongsTo('App\Role', 'role')->withDefault();
    }
    

    https://laravel.com/docs/5.5/eloquent-relationships#one-to-many-inverse

    然后使用 ->role()->first() 而不是 ->role . ->role() 直接使用关系。 -&燃气轮机;角色 首先尝试使用对象的属性,如果该属性不存在,则加载相关数据(对象或集合)。由于用户对象具有role属性,Laravel使用它而不是加载相关的role对象。