简体   繁体   English

Laravel:如何在另一个表的所有行中以数组格式获取M:M关系的特定列数据

[英]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.

相关问题 Laravel 5数据库关系-在另一个表上获取数据 - Laravel 5 database relationship - get data on another table Laravel从关系的关系表中获取数据并选择列? - Laravel Get data from relationship's relationship table and select column? 在 Laravel 中,如何从我的 API Controller 内的*表*返回特定的*列*? 我正在使用 Laravel 5 - In Laravel, how can i return a specific *column* from a *table* inside my API Controller ? I'm using Laravel 5 Laravel,从表中获取特定列的数据并将其存储在另一个表中的不同列名中 - Laravel, get data of a specific column from table and store it in a different column name in another table 我正在尝试使用 Eloquent 获取特定用户的关注者,从 Laravel 中的多对多关系 - I'm trying to get the Followers of a specific user with Eloquent, from a many to many relationship in Laravel 如何从Laravel Eloquent中的HasMany关系中的联接表中获取特定列 - How to get a specific column from the joined table in HasMany relationship in Laravel Eloquent 如何在laravel5中获取另一个表的列数据? - How to get column data of another table in laravel5? Laravel / Eloquent / Query builder使用多对多关系时如何从另一个表中获取所有书籍 - How to get all books from another table when using many to many relationship Laravel / Eloquent / Query builder Laravel Models Pivot表1-1关系应为1-M - Laravel Models Pivot Table 1-1 Relationship should be 1-M Laravel,将行复制到另一个具有雄辩关系的表 - Laravel, copy row to another table with eloquent relationship
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM