编程语言
首页 > 编程语言> > PHP-Kohana 3 ORM as_array返回ORM数组

PHP-Kohana 3 ORM as_array返回ORM数组

作者:互联网

我正在执行一个简单的查询,并想找回一个数组.
基于Kohana 3指南随附的ORM教程,我认为我可以执行以下操作:

ORM::factory('user')->find_all()->as_array();

但这似乎给了我一个模型对象数组(即array(User_Model1,User_Model2 …

查看源代码,我发现可以通过以下补丁来轻松解决此问题.

modules/database/classes/kohana/database/result.php
@@ -94,7 +94,7 @@
                        foreach ($this as $row)
                        {
-                               $results[] = $row;
+                               $results[] = $row->as_array();

这似乎更符合用户指南的内容:

A powerful feature of ORM is the ORM::as_array method which will return the given record as an array. If used with ORM::find_all, an array of all records will be returned. A good example of when this is useful is for a select list:

// Display a select field of usernames (using the id as values) echo
Form::select(‘user’, ORM::factory(‘user’)->find_all()->as_array(‘id’, ‘username’));

想知道这是否是故意的吗?
如果我确实想创建一个关联数组的数组,会有什么更好的解决方法?

解决方法:

这是故意行为,如在文档中可见(很明显?),因此请不要应用该“补丁”.尤其是因为您要修改ORM(不仅是)本身.

相反,请阅读以下内容:

>如果将as_array()应用于行集合,则会返回行数组(每行都是单独的对象,而不是数组),
>如果应用于单行,它将返回该行作为数组,

因此,您至少有两个解决方案:

>将集合转换为数组后,显式地转换每一行,
>在代理类中添加您自己的methon,而不用更改模块代码(Kohana具有从核心类继承的空类,您可以通过将其放置在应用程序/类中来覆盖它们).

这个特定的类称为Kohana_Database_Result,因此将类Database_Result放在application / class / database / result.php中,并使其继承自Kohana_Database_Result,然后更改所需内容(如果需要更改).

标签:kohana-3,orm,kohana-orm,php
来源: https://codeday.me/bug/20191209/2095816.html