我将关系保存到一个数据透视表,该数据透视表将helpdesk_ticket连接到user_id,并附加一列描述他们上次查看故障单的时间。我找到了一个解决方案,但我正在寻找一种方法来优化它,因为它似乎有点hacky。
我发回的对象是与所附用户关系的已保存关系。
$involved = HelpdeskTicketInvolved::where('helpdesk_ticket_id', $ticket_involved_user->helpdesk_ticket_id)->where('users_id', $ticket_involved_user->users_id)->with('user')->first();
正如预期的那样,我得到了以下对象。
{
"id": 27,
"helpdesk_ticket_id": 1,
"users_id": 20,
"ticket_notifications": 1,
"ticket_emails": 1,
"created_at": "2017-06-26 10:13:00",
"updated_at": "2017-06-26 10:13:00",
"viewed_at": null
"user": {
"id": 20,
"name": "Nate",
"username": "nate",
"email": "nate@email.com",
"config": "",
"ad_connected": true,
"is_store": false,
"force_reset": false,
"disabled": false,
"last_login": "2017-01-19 08:05:00",
"created_at": "2016-10-04 18:15:00",
"updated_at": "2017-05-31 12:00:00",
"phone": null,
"district_id": null,
"deleted_at": null,
}
}
我真的想要颠倒对象的顺序,以便让用户回过头来保存关系,就像我在下面一样。
{
"id": 20,
"name": "Nate",
"username": "nate",
"email": "nate@email.com",
"store_id": 89,
"config": "",
"ad_connected": true,
"is_store": false,
"force_reset": false,
"disabled": false,
"last_login": "2017-01-19 08:05:00",
"created_at": "2016-10-04 18:15:00",
"updated_at": "2017-05-31 12:00:00",
"phone": null,
"district_id": null,
"deleted_at": null,
"pivot": {
"id": 27,
"helpdesk_ticket_id": 1,
"users_id": 20,
"ticket_notifications": 1,
"ticket_emails": 1,
"created_at": "2017-06-26 10:13:00",
"updated_at": "2017-06-26 10:13:00",
"viewed_at": null
}
}
以下是我现在正在使用的代码,但是我对它不满意。什么是优化此方法的最佳方式?
$involved = HelpdeskTicketInvolved::where('helpdesk_ticket_id', $ticket_involved_user->helpdesk_ticket_id)->where('users_id', $ticket_involved_user->users_id)->with('user')->first()->toArray();
$return = $involved['user'];
$return['pivot'] = $involved;
unset($return['pivot']['user']);
return Response::json($return, 200);
答案 0 :(得分:1)
如果我理解正确,你可能会得到你所需要的:
User::with("helpdeskTicketInvolved")->find($userid); // Assuming you know the user id you want.
这假设您的用户模型中包含:
public function helpdeskTicketInvolved() {
return $this->hasMany(HelpdeskTicketInvolved::class)->withPivot(["ticket_notifications","ticket_emails"])->withTimestamps();
}