Search code examples
cakephprelationships

Using the recursive model attribute in CakePHP


I'm using CakePHP 2.0 and MySQL. I have the following tables:

Stores
-id
-name
-suburb_id

Outlets
-id
-name
-suburb_id

Suburbs
-id
-name
-state_id

States
-id
-code
-name

States hasMany Suburbs and Suburbs hasMany stores. When I perform the following find:

$this->Outlet->recursive = 0;
$stores = $this->Store->find("all", array('limit' => 50));

It retrieves the Outlet, Suburb, Store and State data arrays.

[Outlet] => Array
(
    [id] => 3
    [name] => SMOKEYS KEBABS PIZZA /PIDE
    [suburb_id] => 1212
)
[Suburb] => Array
(
    [id] => 1212
    [state_id] => 1
    [name] => Wiangaree
    [State] => Array
    (
        [id] => 1
        [code] => ACT
        [name] => Australian Capital Territory
    )
    [Store] => Array
    (
        [0] => Array
        (
            [id] => 12814
            [name] => Wiangaree General Store
            [suburb_id] => 1212
        )
    )
)

Is there anyway to control what it retrieves? Essentially, I would like the Outlets, related Suburb data and related state data.

Or am I going about this incorrectly? The other option I thought of would be implemented ad hoc joins.


Solution

  • When dealing with related models, say modelA and modelB, if you want to use find() with modelA, you should set the recursive property in that model, not in modelB.

    Thus in your code you should set it like this:

    $this->Store->recursive = 0;
    $stores = $this->Store->find("all", array('limit' => 50));
    

    You can also have more control over what is retrieved using the Containable behavior or the fields option of the find()method.