1

ユーザーとグループ用の HABTM があります。グループ ビューに表示したい - ユーザーに属するすべてのグループ。別の言い方をすれば、ユーザーを持つすべてのグループです。

私は MVC に絡まっていて、それを理解することができません。ここに私の 2 つのモデルがあります: class Course extends AppModel

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

と...

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

データベース内のテーブル名はcourses_users- このテーブルにはグループ ID とユーザー ID が格納されています。

十分に単純なはずですが、私は CakePHP を初めて使用するので、助けていただければ幸いです。ありがとうございました!

4

1 に答える 1

2

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.

于 2013-11-12T16:54:32.660 に答える