CakePHP: grab only the data you need

When dealing with an abstraction that outputs dynamic SQL “behind your back”, it’s often easy to forget that some of the queries are… too greedy and grab unneeded data. Here is how to ask for less data, using CakePHP.

Today, I listed only name and id fields of a Model, and to restrict the findAll() to those things:

`$data = $this->Thing->findAll( aa("Thing.user_id", $user_id), a("id", "name"), null, null, null, -1 );`

Breaking down the call, we have:

aa() is a CakePHP convenience function to make an associative array. Odd parameters are keys, even params values. The parameters here creates a WHERE clause that matches the current user’s Things.

a() does the same for regular arrays. The params list the two fields we need returned.

A couple of null settings, and then the crucial -1, which turns off the Model associations completely.

Grab less data!

Update: here is how to use unbindModel. First take a look at the Thing model definition, courtesy of Mladen Mihajlovic:


 array(
      ‘className’ => ‘AnotherThing’
    ),
    ‘SomeOtherThing’ => array(
      ‘className’ => ‘SomeOtherThing’
    ),
    ‘YetAnotherThing’ => array(
      ‘className’ => ‘YetAnotherThing’
    )
  );
}
?>

Now, in our controller, before calling findAll, we remove two of the associated Models:


$this->Thing->unbindModel( array( "hasMany" => array( "AnotherThing", "SomeOtherThing" ) ) );

[tags]cakephp[/tags]

About olleolleolle

Simple guy. Swedish.
This entry was posted in PHP and tagged . Bookmark the permalink.
blog comments powered by Disqus