Laravel eloquent query to get data from M:M relationship
person_table : id, name_of_person
skills_table : id, name_of_skill
M:M table : person_table_id , skills_table_id
and result will be
{
id: 1,
name: harat,
skills: [
'php',
'laravel',
'reactjs',
'nodejs',
]
}
If you check the documentation , you will see that you can use with
so you can eager load the skills
.
So, you should have a code like this:
$person = Person::with('skills')->first();
And then if you do $person->skills
you should have a Collection
(not an array) holding all the Skills like this id: 1, name: php
, id:2, name: laravel
, etc.
So, you should format your resulting models like:
$person->map(function (Person $person) {
return [
'id' => $person->id,
'name' => $person->name,
'skills' => $person->skills->pluck('name'),
];
});
You can also take advantage of API Resources
so you can format your output.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.