You can try pluck, to get just skill_id.
May 24, 2021
9
Level 63
Query with() retrieving only an array of ids from the relationship
Hello,
I have a many-to-many relationship and I'd like to retrieve the items of the relationship like this.
$trainer = Trainer::with(['skills' => function($query) {
$query->select('id');
}])->find($id);
I retrieve this ...
"skills":[{"id":1,"pivot":{"trainer_id":8,"skill_id":1}},{"id":9,"pivot":{"trainer_id":8,"skill_id":9}},{"id":10,"pivot":{"trainer_id":8,"skill_id":10}}]
... but I'd like to retrieve only an array of the skills ids.
"skills":[1, 9, 10]
I know how to retrieve this with another distinct query, but is it possible to get what I want using a query like this one above ?
Thanks for your help ;).
V
Level 122
This way won't have the pivot data
$trainer = Trainer::find($id);
$trainer->skillkeys = $trainer->skills()->pluck('id')->toArray();
return $trainer;
Please or to participate in this conversation.