[英]Eloquent Model's relations not working; Not even a query
如下面的代码所示,我在一个儿童-父母关系中有一个用户和一个角色模型。 发生的事情是我可以通过父母访问孩子,反之亦然。 访问孩子的角色($ 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。
由于您未遵循Laravel命名约定 ,因此需要手动定义外键。 因此,将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使用它而不是加载相关的角色对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.