雄辩模式的关系不起作用;甚至不是查询

问题描述 投票:2回答:1

我在子父关系中有一个User和一个Role模型,如下面的代码所示。会发生什么是我可以通过父母访问孩子,但反之亦然。访问子角色($ user-> role)只能获得ID。角色列在角色表上有一个外键,但相反的方法不起作用。基本上,$ role包含所有用户$ user-> role不显示用户的角色,只显示他的id

Laravel-Debugbar还显示用户不执行额外查询,而角色则执行。

用户表

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。

php laravel eloquent laravel-eloquent
1个回答
5
投票

由于您没有关注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对象。

© www.soinside.com 2019 - 2024. All rights reserved.