I specify that I'd like to do this to dyamically display checkboxes to select some datas joined by a many-to-many relationship, each data having a name and an extra pivot value.
May 27, 2021
7
Level 63
Query to retrieve an array with the primary key as the array key ?
Hello,
I try to write a query to retrieve an array where the array key is the primary key of each element of the query result.
Here is my query.
$teachingUnit = TeachingUnit::with('subjects')->find($id);
$teachingUnit->subjectIds = $teachingUnit->subjects()->pluck('subject_id');
return $teachingUnit;
And here is the result of my query.
{
"id":8,
"name":"Langages de balisage et de feuille de styles",
"hours_number":"50.0",
"comments":"il manque encore un formateur",
"training_id":1,
"created_at":"2021-05-08T13:22:02.000000Z",
"updated_at":"2021-05-24T16:30:59.000000Z",
"subjectIds":[1,2],
"subjects":[
{
"id":1,
"name":"HTML \/ CSS","society_id":2,
"created_at":"2021-05-08T13:56:34.000000Z",
"updated_at":"2021-05-26T20:11:22.000000Z",
"pivot":
{
"teaching_unit_id":8,
"subject_id":1,
"hours_number":"20.0"
}
},
{
"id":2,
"name":"Javascript \/ VueJS","society_id":2,
"created_at":"2021-05-08T13:56:44.000000Z",
"updated_at":"2021-05-08T13:56:44.000000Z",
"pivot":
{
"teaching_unit_id":8,
"subject_id":2,
"hours_number":"30.0"
}
}
]
}
Is it possible to modify the query to obtain this ?
{
"id":8,
"name":"Langages de balisage et de feuille de styles",
"hours_number":"50.0",
"comments":"il manque encore un formateur",
"training_id":1,
"created_at":"2021-05-08T13:22:02.000000Z",
"updated_at":"2021-05-24T16:30:59.000000Z",
"subjectIds":[1,2],
"subjects":
[
1 => // that's the subject primary key
{
"name":"HTML \/ CSS",
"hours_number":"20.0"
},
2 => // that's the subject primary key
{
"name":"Javascript \/ VueJS",
"hours_number":"30.0"
}
]
}
I know how to do in pure PHP, but I have really no idea if it is possible to obtain this via an Eloquent query.
Thanks for your answer ;).
Vincent
Level 75
map or mapWithKeys from collection.
2 likes
Please or to participate in this conversation.