简体   繁体   English

Laravel eloquent 与 json 的关系作为字符串(只有一个属性)

[英]Laravel eloquent relation to json as string (only one attribute)

When I serialize a model (eg ModelA ) that has a relation (eg ModelB ), it looks something like this:当我序列化具有关系(例如ModelB )的 model (例如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"
    }
}]

Instead I want to compress the relation since there's only one useful information to something like this:相反,我想压缩关系,因为只有一个有用的信息是这样的:

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

This behavior however should only occur when it's serialized as a relation but not if it's the top-level model.然而,这种行为应该只在它被序列化为关系时才会发生,但如果它是顶级 model 则不会发生。 Is it possible to configure that inside the relation instead of an accessor in the parent model or modifing the resulting collection afterwards?是否可以在关系内部配置它而不是父 model 中的访问器或之后修改结果集合?

in your model1 overwrite the function called toArray and add custom your column something like this:在你的 model1 中覆盖名为 toArray 的 function 并添加自定义列,如下所示:

public function toArray()
{
    $array = parent::toArray();
    $array['modelB'] = $this->modelB()->first()->name;
    return $array;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM