I have a hasMany relation function like this:

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

And use it like this:

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

我对它没有任何问题,因为它返回了预期的数据.大概是这样的:

{
"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
    }
 ]
}

我试图实现但仍然无法实现的是,仅获取关系字段的一个子集即可获得:

{
"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.

这可能吗?

推荐答案

是的,有可能.你有几个 Select .

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

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

     $data = \App\User::with(['articles' => function($query) {
         // user_id is required here*
         $query->select(['id', 'title', 'user_id']);
     }])->get();
    
  2. 创建包含所需字段的新关系.

     public function articleTitles() {
         // user_id is required here*
         return $this->hasMany('App\Article')->select(['id', 'title', 'user_id']);
     }
    
     $data = \App\User::with('articleTitles')->get();
    
  3. 如果只关心数组/json输出,可以修改App\Article模型,使其在转换为数组时仅显示id和标题.

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

你 Select 什么取决于你需要什么.

Laravel相关问答推荐

Laravel 数据未传递到下拉框

如何返回Blade Laravel 中的按钮?

如何使用 laravel 更新单个值

Laravel & Docker:无法打开流或文件/var/www/html/storage/logs/laravel.log:无法打开流:权限被拒绝

为什么 Laravel 5 会自动更新我的日期字段?

Laravel 5.4 LengthAwarePaginator

使用 Laravel Socialite 登录 Facebook

合并和排序两个 Eloquent 集合?

Laravel whereDoesntHave() - 多个 OR 条件

Laravel - 自定义时间戳列名称

何时在 Laravel 中使用 Repository vs Service vs Trait?

在 php Laravel 5 中创建自定义帮助函数的最佳实践是什么?

加载模型的所有关系

Laravel:自定义或扩展通知 - 数据库模型

在Lumen框架中启用会话

扩展 Eloquent 的类的构造函数

WhereHas Laravel 中的关系计数条件是什么

Laravel 的 toSql() 方法是否会屏蔽 id? (列值被问号替换)

为什么 phpunit 没有得到 phpunit.xml 中指定的正确 APP_ENV?

如何在 Laravel 5 请求类中使用有时规则