在hasMany关系上获取特定字段

编程入门 行业动态 更新时间:2024-10-19 07:31:36
本文介绍了在hasMany关系上获取特定字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个像这样的 hasMany 关系函数:

I have a hasMany relation function like this:

public function articles() { return $this->hasMany('App\Article'); }

并像这样使用它:

$data = \App\User::with('articles')->get();

我没有任何问题,因为它正在返回预期的数据.像这样:

I don't have any problems with it, since it's returning the expected data. Something like this:

{ "id": 1, "name": "Jhon", "lastname": "Doe", "articles": [ { "id": 1, "title": "Article 1", "status": "published", "published_at": "2015-04-30" }, { "id": 2, "title": "Article 2", "status": "draft", "published_at": null } ] }

我想要实现的目标,但我仍然不能仅获取关系字段的子集来获取此信息:

What I am trying to achieve but I still can't it's to fetch just a subset of the relation's fields to obtain this:

{ "id": 1, "name": "Jhon", "lastname": "Doe", "articles": [ { "id": 1, "title": "Article 1" }, { "id": 2, "title": "Article 2" } ] }

我的目的是找到一种在模型函数中指定字段子集的方法,而不是迭代返回的集合并取消设置不需要的字段.

My intention is to find a way to specify the subset of fields in the Model's function instead of iterating the returning collection and unset the unwanted fields.

这可能吗?

推荐答案

您有几个选择:

  • 使用时修改关系查询. with()方法可以接受键/值对的数组,其中键是关系的名称,值是用于修改关系查询的闭包.

  • Modify the relationship query when using it. The with() method can accept an array of key/value pairs where the key is the name of the relationship and the value is a Closure that modifies the relationship query. $data = \App\User::with(['articles' => function($query) { $query->select(['id', 'title', 'user_id']); }])->get();

  • 创建一个包含所需字段的新关系.

  • Create a new relationship that contains the fields you want.

    public function articleTitles() { return $this->hasMany('App\Article')->select(['id', 'title', 'user_id']); } $data = \App\User::with('articleTitles')->get();

  • 如果仅关注array/json输出,则可以修改App \ Article模型以仅在转换为数组时显示id和标题.

  • If you're only concerned about the array/json output, you can modify the App\Article model to only display the id and title when converted to an array.

    class Article extends Model { protected $visible = ['id', 'title']; }

  • 选择什么取决于您的需求.

    What you choose depends on what you need.

    注意:对于上述选项1和2,必须选择外键(user_id),以便Laravel知道在建立关系时如何将模型链接在一起.

    NB: For options 1 and 2 above, the foreign key (user_id) must be selected so that Laravel knows how to link the models together when building the relationships.

    更多推荐

    在hasMany关系上获取特定字段

    本文发布于:2023-10-24 20:15:26,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1524897.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:字段   关系   hasMany

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!