简体   繁体   中英

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.

You can create toArray method for City model to get city in valid format like this:

public function toArray()
{
   return [
      'key' = $this->id,
      'title' => $this->name,
   ];
}

or if you need more data here you can use:

public function toArray()
{
   $data = parent::toArray();
   $data['key'] = $data['id'];
   unset($data['id']);
   $data['title'] = $data['name'];
   unset($data['name']);
   return $data;
}

and it should do the trick. But obviously you cannot do anything with situation when key or title will be added to table and you would like to return also them because they will be overriden by id and name you assigned to those keys.

I've done it via attribute Accessors.

Not sure this answers your question in whole or in part, but its an approach to think about. Recently i've been using the Presenter Pattern.

laracasts/Presenter

A presenter is just a class that bolts onto your model object with methods that transform and/or formats the data.

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