cakephpcontainable

CakePHP Containable error: a two level association doesn't work


I do the next query:

        $this->find('all',array(
            'contain' => array(
                'User' => array('id','facebook_id','name','username','Author' => array('first_name','last_name','code','photo')),
                'Tab.code'
            ),
            'fields' => array('Comment.date','Comment.time','Comment.content'),
            'conditions' => array(
                'Tab.code' => $code
            ),
            'limit' => $limit,
            'offset' => $offset
        ));

Comment...

    public $belongsTo = array(
        'User' => array('foreignKey' => 'user_id'),
        'Tab' => array('foreignKey' => 'tab_id')
    );

User...

    public $hasOne = array('Author' => array('foreignKey' => 'id'));

and Author...

    public $belongsTo = array(
        'User' => array(
            'className' => 'User',
            'foreignKey' => 'id'
        )
    );

This returns something like this (in json)...

[
    {
        "Comment": {
            "date": "2001-12-15",
            "time": "17:32:12",
            "content": "..."
        },
        "User": {
            "id": "29",
            "facebook_id": "1234",
            "name": "User 29",
            "username": "user29"
        },
        "Tab": {
            "code": "llibre-de-prova-29",
            "id": "229"
        }
    }
    ...
]

...while I expect that attached to User appears an Author with the fields I specified. Do you know why Author doesn't appear? I did other contains with two levels of recursivity on the code and all works as expected.

Thank you for your help and attention!


Solution

  • Make sure that your model has the Containable behavior attached. It should include the following line:

    $actsAs = array('Containable');
    

    Pay attention to make sure that you didn't omit an "s" in "acts" which is a common typo that is hard to spot. You can also attach the Containable behavior on the fly like this:

    $this->YourModel->Behaviors->attach('Containable');
    $this->YourModel->find('all', array('contain' => array(...)));
    

    Also make sure you type "contain" as the array key, not "contains".