Otaqui.Com

Pete Otaqui’s blog about web development and everything else

Custom Model and Field Result Set in CakePHP

one comment

If you’re using CakePHP and want to perform a custom SQL query while forcing your results into an arbitrary Model-based array when they are given back to you, you could do a lot worse than using grigri’s (who is a fellow South Westerner and therefore obviously a good bloke ;) DboMysqlEx (Mysql Extended) Class, or at least this particular part of it:

<?php
require_once (LIBS . 'model' . DS . 'datasources' . DS . 'dbo' . DS . 'dbo_mysql.php');
class DboMysqlEx extends DboMysql {
   var $description = "MySQL DBO Driver - Extended";
   // Override resultSet to allow for Model__field type aliases
   function resultSet(&$results) {
		if (isset($this->results) && is_resource($this->results) && $this->results != $results) {
			mysql_free_result($this->results);
		}
       $this->results =& $results;
       $this->map = array();
       $num_fields = mysql_num_fields($results);
       $index = 0;
       $j = 0;
       while ($j < $num_fields) {
           $column = mysql_fetch_field($results,$j);
           if (!empty($column->table)) {
               $this->map[$index++] = array($column->table, $column->name);
           } else {
               if (strpos($column->name, '__')) {
                   $parts = explode('__', $column->name);
                   $this->map[$index++] = array($parts[0], $parts[1]);
               } else {
                   $this->map[$index++] = array(0, $column->name);
               }
           }
           $j++;
       }
   }
}
?>

This code, which overrides the default MySQL DBO, allows you to SELECT something AS Modelname__Fieldname (with a double underscore) and will end up populating your result set as you would like it to ($results['Modelname']['Fieldname']).

In order to use a custom datasource, copy the code and save it as “/cake_dir/app/models/datasources/dbo/dbo_mysqlex.php” and edit your “/cake_dir/app/config/database.php” file so that it uses the “mysqlex” driver instead of plain old “mysql”.

This all came from a discussion on the excellent CakePHP Google Group

Grigri posted a copy of his modified MySQL Extended DBO online if you want some more of his nice features like backtracing.

Written by pete

February 6th, 2009 at 1:22 am

Posted in Professional

Tagged with ,

One Response to 'Custom Model and Field Result Set in CakePHP'

Subscribe to comments with RSS or TrackBack to 'Custom Model and Field Result Set in CakePHP'.

  1. Awesome, that totally solves the problem. Thank you!

    I hope there won’t be any problems with this workaround in future CakePHP versions.

    Michael

    22 Jul 09 at 4:06 am

Leave a Reply