Php – Kohana 3 ORM as_array return array of ORM

kohana-3kohana-ormormPHP

I'm executing a simple query and want to get an array back.
Based on the ORM tutorial that comes with the Kohana 3 guide, I thought I could do the following:

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

But that seems to give me an array of model objects (ie array( User_Model1, User_Model2 …

Looking at the source I see I can easily fix this by hacking with the following patch.

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

Which seems to be more in line with what the user guide says:

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'));

Wondering if this is intentional, if so, why?
What would be a better work around if I do want to create an array of associative arrays?

Best Answer

This is intentional behaviour, as (clearly?) visible in the documentation, so please do not apply that "patch". Especially because you want to modify ORM (not only) itself.

Instead read this:

  • if as_array() is applied on the collection of rows, it returns array of rows (each row being separate object, not array),
  • if applied on single row, it returns the row as an array,

So you have at least two solutions:

  • transform each row explicitly after transforming collection to array,
  • add your own methon in the proxy class instead of changing the module code (Kohana has empty classes that inherit from core classes and that you can override by placing them in application/classes).

This specific class is called Kohana_Database_Result, so place class Database_Result in application/class/database/result.php and make it inherit from Kohana_Database_Result, then change what you need (if you need to change that).

Related Topic