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