Q:

Joining tables in Cakephp

I'm exploring cakePHP and trying to get a join to work but failing.  Any help is appreciated!   The situation:  I have one users table and one timeslots table.  Each timeslot is set up to hasMany users (timeslot is meant to have 2 users meet):
var $hasMany = array(
 'Partner' => array(
  'className' => 'User',
  'foreignKey' => 'id'
 ),
'Student' => array(
  'className' => 'User',
  'foreignKey' => 'id'
 )
);

So, what I want to do is load a timeslot, and join the users table to populate who the 'Partner' is and who the 'Student' is.   Right now I've got the join set up this way (for the student):
    $params = array(
        'joins' => array(
            array(
                'table' => 'users',
                'alias' => 'User',
                'type' => 'LEFT',
                'conditions' => array(
                    'User.id = Timeslot.student_id',
                )
            )
        )
    );
    $this->set('timeslots', $this->Timeslot->find('all', $params)); 

In my timeslots variable when I get to the view I have an array for Partner and an array for Student, due to the $hasMany association.  But I can't figure out how to get those variables loaded in the appropriate way!
Thanks for your help!   

A:

welcome to CakePHP!  
It looks like your relationship is set up incorrectly.  Based on your description, a timeslot would have one parter and one student. As such, the relationship that should be defined is a belongsTo.  Your timeslot table should have two foreign keys, partner_id and student_id.  Then in your timeslot model, declare:
var $belongsTo = array(
    'Partner' => array(
        'className' => 'User',
        'foreignKey' => 'partner_id'
    ),
    'Student' => array(
        'className' => 'User',
        'foreignKey' => 'student_id'
    )
);

The should result in a call to $this->Timeslot->find() returning something like:
array(
    0 => array(
        'Timeslot' => array(...),
        'Partner' => array(...),
        'Student' => array(...)
    ),
    1 => array(
        'Timeslot' => array(...),
        'Partner' => array(...),
        'Student' => array(...)
    ),
    ...
)

Is that what you're trying to get to?

