在hasMany关系上获取特定字段 [英] Fetch specific fields on a hasMany relation
问题描述
我有一个像这样的 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关系上获取特定字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!