【发布时间】:2015-11-12 09:58:16
【问题描述】:
我有一个属于许多用户的模型角色。
Class Role {
public $fillable = ["name"];
public function users()
{
return $this->belongsToMany('App/Models/User')->select(['user_id']);
}
}
当我在角色中使用 with 查询检索用户时。我希望它只返回 user_ids 数组
Role::with("users")->get();
它应该返回以下输出
[
{
"name": "Role1",
"users" : [1,2,3]
},
{
"name": "Role2",
"users" : [1,2,3]
}
]
目前它给出以下输出
[
{
"name": "Role1",
"users" : [
{
user_id : 1
},
{
user_id : 2
},
{
user_id : 3
}
},
{
"name": "Role2",
"users" : [
{
user_id : 1
},
{
user_id : 2
},
{
user_id : 3
}
]
}
]
【问题讨论】:
-
您也许可以使用
->lists('user_id')而不是->all()来实现它。 -
试试这个 return $this->belongsToMany('App/Models/User')->lists('user_id');
-
对不起,我使用的是“->get”而不是“->all”。我已经编辑了我的问题。 @Jeemusu,它为所有记录提供 id 数组,我需要每个角色的 user_ids
-
@Creator 我尝试过使用列表但不起作用
标签: php mysql laravel eloquent relationship