itamar
itamar

Reputation: 3967

Getting All groups that belong to user

I have HABTM for Users and Groups. I want to show in a Group view - all the Groups that belong to a User. Or to put it differently - all the Groups that have the User.

I am getting tangled in the MVC and am not able to figure it out. Here are my two models: class Course extends AppModel

  public $name = 'Course';
  public $hasAndBelongsToMany = array('User' =>
            array(
                'unique' => false
            )
            );

And...

 public $name = 'User';
  public $hasAndBelongsToMany = array('Course' =>
            array(
                'unique' => true
            )
            );

The table name in the database is courses_users - this table houses group ids and user ids.

Should be simple enough but I'm new to CakePHP so I'd love some help. Thank you!

Upvotes: 1

Views: 88

Answers (1)

Kai
Kai

Reputation: 3823

CakePHP has recursive set to 1 by default, which means that assuming you have not changed the recursive setting, it will automatically fetch all associated courses when you call find on a user, assuming you set up the HABTM relationship when doing the find. Therefore, all you have to do is:

$this->User->find('first', array('conditions' => array('User.id' => $this->Auth->user('id'))));

In your User model, I don't think it's strictly necessary, but I like to specify the join table and such on HABTM relationships:

public $hasAndBelongsToMany = array('Course' =>
        array(
            'unique' => true,
            'dependent' => false,
            'joinTable' => 'courses_users',
            'foreignKey' => 'user_id',
            'associationForeignKey' => 'course_id',
        )
    );

Keep in mind that in HABTM relationships, you don't ever really touch the joinTable beyond specifying which table to use as the joinTable when setting up the relationship. CakePHP will automatically do the rest of the work.

Upvotes: 2

Related Questions