Question

I'm having an issue using WanWizard's DataMapper 1.8.2. I want to get an array of results after get(). The following snippet shows how I have been able to do it vs. how I want, and as far as the documentation has claimed, should be able to do it.

        $arr = $loc->get();
//  THIS WORKS
//        $results = array();
//        foreach($arr as $item) {
//            $results[] = $item->stored;
//        }
        $results = $arr->all_to_array();  // THIS DOES NOT WORK
        $results = $loc->all_to_array();  // THIS ALSO DOES NOT WORK

When I use the "$results = $arr->all_to_array();" call, an exception is thrown. Here is the exception output in syslog:

PHP Fatal error:  Uncaught exception 'Exception' with message 'Unable to call the method "all_to_array" on the class Location' in /var/www/imhere/application/libraries/datamapper.php:1188\nStack trace:\n#0 /var/www/imhere/application/controllers/locations.php(66): DataMapper->__call('all_to_array', Array)\n#1 /var/www/imhere/application/controllers/locations.php(66): Location->all_to_array()\n#2 [internal function]: Locations->index_get()\n#3 /var/www/imhere/application/libraries/REST_Controller.php(424): call_user_func_array(Array, Array)\n#4 /var/www/imhere/application/libraries/REST_Controller.php(411): REST_Controller->_fire_method(Array, Array)\n#5 /var/www/imhere/system/core/CodeIgniter.php(325): REST_Controller->_remap('index', Array)\n#6 /var/www/imhere/index.php(208): require_once('/var/www/imhere...')\n#7 {main}\n  thrown in /var/www/imhere/application/libraries/datamapper.php on line 1188

Has anyone else dealt with this?

Secondly, the reason why I want to use the all_to_array method is that I am using a select function with an alias, but it is not showing up when I use $item->stored. Will using all_to_array return values that are not explicit database columns?

Was it helpful?

Solution

You need to make sure the array extension is loaded: http://datamapper.wanwizard.eu/pages/extensions.html

You can either do this globally in the DataMapper config file:

$config['extensions'] = array('array');

Or on the model itself:

class Location extends DataMapper {

    var $extensions = array('array');

    // ...
}

or dynamically at runtime:

$location = new Location();
$location->load_extension('array');
$results = $location->get()->all_to_array();

That will get rid of the error!

To answer your second question: you shouldn't really need to access the stored property, and you don't need to return the results as an array either. Use Object-Oriented programming! :)

The best way of achieving what you want to do is to keep the results as objects, then, when looping through them, simply call the property you're after. Then you can keep the code pretty clean:

$locations = new Location();
$locations->get();
foreach( $locations as $location ) {
    echo $location->property;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top