vendredi 23 mars 2018

Merging multiple Eloquent models keeping newest one but filling out blank attributes with other model

Lets say I've got 3 Eloquent models which I want to merge to one model.

The newest model should be the base model, from which I want to fill blank attributes with the (possible) data from the other two models.

So:

id | created_at | name     | location | favorite_piza | drink | pet
5  | 2018-03-22 | John Doe |          |               | Beer  |
2  | 2017-02-12 | John Doe | Earth    | Hawai         |       |
1  | 2012-01-01 | J. Doe   |          | Margarita     |       | Dog

Result:

5 | 2018-03-22 | John Doe  | Earth    | Hawai         | Beer  | Dog

Off course I could loop through all the known attributes and traverse each not-newest model to see if the attribute is set...

But that sounds a little bit cumbersome; there should be a better way to aggregate these models to one, with the newest as base.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire