mardi 20 décembre 2016

Laravel Model: how to get all relations as array with custom array keys?

I have two tables: countries and cities. Each of them contain columns: id, name, etc. I can get all countries with all their cities as an array:

$countries = Country::with('cities')->select('id', 'name')->get();
$countries->toArray();

Result:

[
  [
     id: 1
     name: Zimbabe
     cities: [[id: 1, name:'Capital City'], /*etc...*/]           
  ],
//etc.
]

But I need different array keys: 'key' and 'title' instead of 'id' and 'name', because of a required javascript component:

[
  [
     key: 1
     title: Zimbabe
     cities: [[key: 1, title:'Capital City'], /*etc...*/]           
  ],
//etc..
]

I think, I can do it via attribute accessors. But what to do, if in the future a new column is added to the table with, for example, a 'key' field? This violates the accessor's logic.

And a second problem: how do I get all model relations with custom array keys?

At this moment I think that the only solution is to manually create a new array via recursion after fetch model result with all relations.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire