I'm saving a relationship to a pivot table that connects a helpdesk_ticket to a user_id with an extra column describing the last time they've viewed the ticket. I've found a solution but am looking for a way to optimize it because It seems a bit hacky.
The object I'm sending back is the saved relationship with the user relationship attached.
$involved = HelpdeskTicketInvolved::where('helpdesk_ticket_id', $ticket_involved_user->helpdesk_ticket_id)->where('users_id', $ticket_involved_user->users_id)->with('user')->first();
As expected I get the following object back.
{
"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,
}
}
I'd really like to reverse the order of the object so that I get the user back with a pivot of the saved relationship like I have below.
{
"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
}
}
So below is the code I'm working with now that works but I'm not happy with it. What's the best way to optimize this?
$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);
If I understand you correctly you might get what you need by doing:
User::with("helpdeskTicketInvolved")->find($userid); // Assuming you know the user id you want.
This assumes that in your user model you have:
public function helpdeskTicketInvolved() {
return $this->hasMany(HelpdeskTicketInvolved::class)->withPivot(["ticket_notifications","ticket_emails"])->withTimestamps();
}