简体   繁体   English

Laravel模型:如何使用自定义数组键将所有关系作为数组?

[英]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: 它们每个都包含列:id,名称等。我可以将所有城市及其城市作为一个数组来获取:

$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: 但是我需要不同的数组键:由于必需的javascript组件,因此需要'key'和'title'而不是'id'和'name':

[
  [
     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: 您可以为City模型创建toArray方法来获取有效格式的城市,如下所示:

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. 但是很明显,当将键或标题添加到表中并且您还希望返回它们时,您无法做任何事情,因为它们将被您分配给这些键的id和名称覆盖。

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. 演示者只是一个使用转换和/或格式化数据的方法附加到模型对象上的类。

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

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