简体   繁体   中英

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:

[{
    "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. Is it possible to configure that inside the relation instead of an accessor in the parent model or modifing the resulting collection afterwards?

in your model1 overwrite the function called toArray and add custom your column something like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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