Eloquent 模型的关系不工作;甚至没有查询

Eloquent Model's relations not working; Not even a query

我在 child-parent 关系中有一个用户和一个角色模型,如下面的代码所示。发生的情况是我可以通过 parent 访问 child,但反之则不行。访问 child 的角色($user->role)只会给我 ID。角色列在角色 table 上有一个外键,但相反的是行不通的。 基本上, $role 包含所有用户 $user->role 不显示用户的角色,只显示他的id

Laravel-Debugbar 还表明用户没有执行额外的查询,而角色执行。

用户table

id name email password remember_token client role created_at updated_at

角色table

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。

由于您没有关注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 首先尝试使用对象的 属性 ,如果不存在,则加载相关数据(对象或集合)。由于 User 对象具有角色 属性,Laravel 使用它而不是加载相关的 Role 对象。