0

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

Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206

2 Answers2

1

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')));
Nik Chankov
  • 6,049
  • 1
  • 20
  • 30
  • Used recursive = 1; and the first line was enough. But could you post an example of how can I get the Containable behavior please? the documentation isn't clear enough. – Christopher Francisco Feb 09 '14 at 18:08
  • Containable behaviour is core behaviour included in the CakePHP. normally I just include it in the AppModel like: public $actsAs = array('Containable', ...); Then you can use it in find as easy as, specifying the relation table. It's good practice, since this way if you have a lot of relations, but you need only few of them, you can lightweight your queries with it. I think Containable behaviour doc, is clear enough: bit.ly/1gjCtRc – Nik Chankov Feb 09 '14 at 23:01
0
 $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)));
Fury
  • 4,643
  • 5
  • 50
  • 80