sp1*_*p11 18 php mysql relationship laravel eloquent
我有一个模型角色,属于许多用户.
Class Role {
public $fillable = ["name"];
public function users()
{
return $this->belongsToMany('App/Models/User')->select(['user_id']);
}
}
Run Code Online (Sandbox Code Playgroud)
当我在Role中检索使用查询的用户时.我希望它只返回user_ids数组
Role::with("users")->get();
Run Code Online (Sandbox Code Playgroud)
它应该返回以下输出
[
{
"name": "Role1",
"users" : [1,2,3]
},
{
"name": "Role2",
"users" : [1,2,3]
}
]
Run Code Online (Sandbox Code Playgroud)
目前它提供以下输出
[
{
"name": "Role1",
"users" : [
{
user_id : 1
},
{
user_id : 2
},
{
user_id : 3
}
},
{
"name": "Role2",
"users" : [
{
user_id : 1
},
{
user_id : 2
},
{
user_id : 3
}
]
}
]
Run Code Online (Sandbox Code Playgroud)
ben*_*enJ 31
就个人而言,我不会改变users()关系,但可能会为用户ID添加一个访问者
class Role {
protected $fillable = ["name"];
// adding the appends value will call the accessor in the JSON response
protected $appends = ['user_ids'];
public function users()
{
return $this->belongsToMany('App/Models/User');
}
public function getUserIdsAttribute()
{
return $this->users->pluck('user_id');
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您仍然具有工作关系,但可以在角色响应中将用户ID作为数组进行访问.如果这对你不起作用,正如@Creator所提到的,你可能只是添加->pluck('id')关系而不是select()