[英]Laravel: How to get specific column data of M:M relationship in array format in all row of a another table
Laravel eloquent query to get data from M:M relationship Laravel eloquent查询从M:M关系中获取数据
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
.如果您查看文档,您将看到可以使用
with
以便您可以立即加载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.然后如果你执行
$person->skills
你应该有一个Collection
(不是一个数组)来保存所有的技能,比如id: 1, name: php
, id:2, name: laravel
等等。
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.您还可以利用
API Resources
来格式化输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.