我有一个表interviewer_id
的列,它等于users表的id
。我根据控制器中的interviewer_id
对数据进行分组,并希望从users表中获取属于每个组的id的名称。这是我试过的
$int_payment = IntPayments::where('month',$month_year)->groupBy('interviewer_id')->get();
foreach ($int_payment as $inter) {
$inters = User::where('id',$inter->interviewer_id)->get();
}
return response()->json(['inters',$inters]);
此处,我的响应仅显示通过User获取的一个组数据。我想从用户表中获取其id
是组ID
这就是我想要的。当我回复$ int_payment时,我得到了这个回应。
["inters",[{"id":2,"candidate_id":"13","interviewer_id":"1","profile_id":"","exp":"5-10","payment_status":"unpaid","month":"Feb 2017","created_at":"2017-02-08 04:56:40","updated_at":"2017-02-08 04:56:40"},{"id":4,"candidate_id":"13","interviewer_id":"2\r\n","profile_id":"","exp":"5-10","payment_status":"unpaid","month":"Feb 2017","created_at":"2017-02-08 04:56:40","updated_at":"2017-02-08 04:56:40"},{"id":1,"candidate_id":"13","interviewer_id":"4","profile_id":"","exp":"5-10","payment_status":"unpaid","month":"Feb 2017","created_at":"2017-02-08 04:56:40","updated_at":"2017-02-08 04:56:40"}]]
如果您看到响应,则有三个组具有ID 2,4和1.这些ID是用户表中用户的ID。我想获得属于ids的用户名。
答案 0 :(得分:3)
尝试在数组中返回$inters
:
foreach ($int_payment as $inter) {
$inters[] = User::where('id',$inter->interviewer_id)->get();
}
return $inters;
但是,设置User和IntPayment模型之间的关系将更容易处理这种情况。请参阅文档Eloquent relationship.
答案 1 :(得分:0)
试试这个:
IntPayments::select('interviewr_TABLE.*', 'users.name')->where('month',$month_year)->leftJoin('users', 'users.id', '=', 'interviewr_TABLE') ->groupBy('interviewer_id')->get()
这里唯一的问题是我不确切知道你的IntPayments表名是什么。
答案 2 :(得分:0)
只需使用Laravel模型关系即可让生活更轻松:
让你User
模特拥有:
public function intpayments(){
$this->hasMany(IntPayments::class, 'interviewer_id');
}
然后您的IntPayments
模型有:
public function user(){
$this->belongsTo(User::class, 'interviewer_id');
}
因此,您可以轻松地检索所需的相同结果:
$inters = IntPayments::where('month',$month_year)->load('user');
然后你可以遍历这个结果来得到你需要的字段:
$result = [];
foreach($inters as $inter)
{
$result[] = $inter->user->name;
}
return $result;
<强>更新:强>
但我只希望该表中的名称列,而IntPayments中的数据是我的第一优先级
好的,你仍然可以使用查询返回的相同结果:
$result = [];
foreach($inters as $k => $inter)
{
$result[$k]['name'] = $inter->user->name; //this is the user's name
$result[$k]['id'] = $inter->id; //this is intPayments's id
$result[$k]['interviewer_id'] = $inter->interviewer_id; //this is intPayments interviewer's 'id
......
}
也许你不知道,$inters
变量的结果会先给你,每个记录来自IntPayments
,然后是User
每个记录。
这意味着inters
自然会像(如果我以json的身份发送回复):
[
{
"id": 1,
"candidate_id": "1",
"interviewer_id": "3"
"user": {
"id": 1,
"name": "second last",
"email": "second@somemail.com",
}
},
{
"id": 2,
"candidate_id": "1",
"interviewer_id": "5",
"user": {
"id": 1,
"name": "first last",
"email": "first@somemail.com",
}
},
.....
]
这意味着您可以根据需要使用此响应并访问所需的字段。
希望这会有所帮助:)