2015-05-04 74 views
2

我有一个的hasMany关系函数这样的具体领域:取上的hasMany关系

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

而且使用这样的:

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

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

这可能吗?

回答

8

你有几个选择:

  1. 使用时修改相关查询。 with()方法可以接受一组键/值对,其中键是关系的名称,值是修改关系查询的Closure。

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

    public function articleTitles() { 
        return $this->hasMany('App\Article')->select(['id', 'title']); 
    } 
    
    $data = \App\User::with('articleTitles')->get(); 
    
  3. 如果你只关心阵列/ JSON输出,可以修改应用程序\文章模型时转换为一个数组,只显示编号和标题。

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

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

+0

我以前尝试过没有成功的选项2,因为它在“文章”中返回空。今天我尝试了选项1,并在“文章”中返回空白。我试过$ query-> orderBy('id','asc');和工作,但与“选择”方法不起作用。 – Tony

+0

@Tony使用选项1或2时,必须确保已将外键包含在select语句('id')中,否则Laravel将不知道如何将对象链接在一起,并且文章属性将始终空着。 – patricus

+1

这是使它工作的一块!在你的评论之后,我这样做了: 'return $ this-> hasMany('App \ Article') - > select(''id','title','user_id']);' Foreign_key是答案。谢谢@patricus – Tony