Laravel eloquent 与 json 的关系作为字符串(只有一个属性)
Laravel eloquent relation to json as string (only one attribute)
当我序列化具有关系(例如ModelB
)的模型(例如ModelA
)时,它看起来像这样:
[{
"id": 1,
"name": "model a1 name",
"modelB": {
"id": 1,
"name": "model b1 name"
}
}, {
"id": 2,
"name": "model a2 name",
"modelB": {
"id": 3,
"name": "model b3 name"
}
}, {
"id": 3,
"name": "model a3 name",
"modelB": {
"id": 2,
"name": "model b2 name"
}
}]
相反,我想压缩关系,因为只有一个有用的信息是这样的:
[{
"id": 1,
"name": "model a1 name",
"modelB": "model b1 name"
}, {
"id: 2",
"name": "model a2 name",
"modelB": "model b3 name"
}, {
"id": 3,
"name": "model a3 name",
"modelB": "model b2 name"
}]
然而,这种行为应该只在它被序列化为关系时发生,但如果它是顶级模型则不会。是否可以在关系内部配置它而不是父模型中的访问器或之后修改生成的集合?
在您的模型 1 中覆盖名为 toArray 的函数并添加自定义您的列,如下所示:
public function toArray()
{
$array = parent::toArray();
$array['modelB'] = $this->modelB()->first()->name;
return $array;
}
当我序列化具有关系(例如ModelB
)的模型(例如ModelA
)时,它看起来像这样:
[{
"id": 1,
"name": "model a1 name",
"modelB": {
"id": 1,
"name": "model b1 name"
}
}, {
"id": 2,
"name": "model a2 name",
"modelB": {
"id": 3,
"name": "model b3 name"
}
}, {
"id": 3,
"name": "model a3 name",
"modelB": {
"id": 2,
"name": "model b2 name"
}
}]
相反,我想压缩关系,因为只有一个有用的信息是这样的:
[{
"id": 1,
"name": "model a1 name",
"modelB": "model b1 name"
}, {
"id: 2",
"name": "model a2 name",
"modelB": "model b3 name"
}, {
"id": 3,
"name": "model a3 name",
"modelB": "model b2 name"
}]
然而,这种行为应该只在它被序列化为关系时发生,但如果它是顶级模型则不会。是否可以在关系内部配置它而不是父模型中的访问器或之后修改生成的集合?
在您的模型 1 中覆盖名为 toArray 的函数并添加自定义您的列,如下所示:
public function toArray()
{
$array = parent::toArray();
$array['modelB'] = $this->modelB()->first()->name;
return $array;
}