laravel 获取 hasMany 关系上的特定字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30022038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:29:40  来源:igfitidea点击:

Fetch specific fields on a hasMany relation

phplaravellaravel-5eloquent

提问by Tony

I have a hasManyrelation function like this:

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

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

And use it like this:

并像这样使用它:

$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.

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

Is this possible?

这可能吗?

回答by patricus

You've got a couple options:

你有几个选择:

  1. 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) {
        // user_id is required here*
        $query->select(['id', 'title', 'user_id']);
    }])->get();
    
  2. Create a new relationship that contains the fields you want.

    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. 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'];
    }
    
  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'];
    }
    

What you choose depends on what you need.

你选择什么取决于你需要什么。



*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.

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

回答by Jesvin

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

// user_id is important in hasmay relationships

// user_id 在 hasmay 关系中很重要