0

I'm trying to retrieve some data through two model relationships with CakePHP. The models and their associations are as follows:

User hasOne Profile HABTM Skill

I would like the user's skills to be returned when I do a find() operation on the User model, and right now it isn't returned. Here's my find call which is being executed against the User model:

$this->paginate = array(
    'conditions' => array(
        'OR' => array(
            'Profile.firstname LIKE' => "%$q%",
            'Profile.lastname LIKE' => "%$q%"
        )
    )
);

It's returning user data and profile data, but not any skill data. I tried setting recursive to 2 or 3, but that doesn't help either. The only way I can get skill data is if I run find() against the Profile model, but I can't do that. For clarification here's the relevant models and their relationships:

// app/Model/User.php
class User extends AppModel {
    public $hasOne = 'Profile';
}

// app/Model/Profile.php
class Profile extends AppModel {
    public $belongsTo = 'User';
    public $hasAndBelongsToMany = 'Skill';

// app/Model/Skill.php
class Skill extends AppModel {
    public $hasAndBelongsToMany = 'Profile';

Can anyone help me get the users skills when retrieving user data? Thanks.

James Dawson
  • 5,309
  • 20
  • 72
  • 126

1 Answers1

1

Use CakePHP's Containable Behavior. Your find will then look something like this:

$this->User->find('all',array(
    'conditions' => array(
        'OR' => array(
            'Profile.firstname LIKE' => "%$q%",
            'Profile.lastname LIKE' => "%$q%"
        )
    ),
    'contain' => array(
        'Profile' => array(
            'Skill'
        )
    )
));

MUCH simpler, easier to read, and voila - you get the data you want without needing to use the dreaded 'recursive'.

Dave
  • 28,833
  • 23
  • 113
  • 183