Question

Quick setup: User hasAndBelongsToMany Course

      courses_users
__________________________
id | user_id | course_id |
 1 |       1 |         1 |
 2 |       1 |         3 |
 3 |       2 |         5 |

I need to load all the Courses for the User with users.id = 1

I tried this:

$this->User->id = $this->Auth->user('id');
$courses = $this->User->Courses->find('all');

But the code above retrieves all the courses instead of the associated to the user's ones

Was it helpful?

Solution

Since your relations are in tact you need to do the following:

$this->User->read(null, $id);
or
$this->User->find('first', array('conditions'=>array('id'=>1)));

And it should return also the courses for the user. It depends from your app, but I would use Containable behaviour to retrieve only the courses, but really depends how many relations you have with user's model.

Having Containable behaviour you should load only Courses relation like that:

$this->User->find('first', 
   array(
      'conditions'=>array('id'=>1), 
      'contain'=>array('Courses')));

OTHER TIPS

 $course_ids = $this->CoursesUser->find('list', array('conditions'=>array('user_id'=>$this->Auth->user('id')), 'fields'=>'course_id'));

 $courses = $this->Course->find('all', array('conditions'=>array('id'=>$course_ids)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top