我有3个模型:组,用户和个人资料
群组涉及具有多对多关系的用户, 用户与一对一关系的个人资料相关, 用户与角色模型有很多关系
问题是如何从一个角色为" mentee"的组中的用户获取配置文件的faculty
属性。 ?
我试过这个,但它没有奏效:
$faculties = collect($this->mentee()->profile->faculty;
这是Group.php
和mentee()
方法
class Group extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
public function mentee()
{
return $this->users()->whereHas(
'roles', function($q){
$q->where('name', 'mentee');
})
->get();
}
这里是User.php
class User extends Authenticatable
{
protected $fillable = [
'username', 'email', 'password',
];
public function profile()
{
return $this->hasOne(Profile::class);
}
public function owns($related)
{
return $this->id == $related->user_id;
}
public function groups()
{
return $this->belongsToMany(Group::class);
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function hasRole($role)
{
if (is_string($role)) {
return $this->roles->contains('name', $role);
}
return !! $this->intersect($this->roles)->count();
}
}
最后,这里是Profile.php
class Profile extends Model
{
protected $fillable = [
'user_id', 'name', 'nim', 'faculty', 'major', 'batch','religion', 'gender', 'phone', 'line_id',
];
public function user()
{
return $this->belongsTo(User::class);
}
}
请告诉我是否应该提供更多详情