HABTM与另一个表的关联

时间:2014-03-16 22:54:33

标签: cakephp has-and-belongs-to-many

我对Cakephp中更复杂的HABTM情况感到麻烦。 Ina nutshel,情况是:一个有用户和电影,之间的关系是HABTM,但我也需要一种关系类型。

USERS - HABTM - MOVIES

          |

    RELATION_TYPES

用户和电影之间的关系可以有多种不同类型:作者类型,公共类型等。

当我尝试使用包含行为时,我收到一条错误消息:

  

Model" MoviesUser"与模型" RelationType"。

无关

但所有模型都是相关的。

这些是模型:

用户模型

public $hasAndBelongsToMany = array(
    'Movie' => array(
        'className' => 'Movie',
        'joinTable' => 'movies_users',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'movie_id',
        'unique' => 'keepExisting',
        'conditions' => '',
        'fields' => '',
        'order' => 'Movie.title',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
        'deleteQuery' => '',
        'insertQuery' => ''
    )
);

电影模型

public $hasAndBelongsToMany = array(
    'User' => array(
        'className' => 'User',
        'joinTable' => 'movies_users',
        'foreignKey' => 'movie_id',
        'associationForeignKey' => 'user_id',
        'unique' => 'keepExisting',
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'finderQuery' => '',
        'deleteQuery' => '',
        'insertQuery' => ''
    )
);

MoviesUser Model

public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Movie' => array(
        'className' => 'Movie',
        'foreignKey' => 'movie_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'RelationType' => array(
        'className' => 'RelationType',
        'foreignKey' => 'relation_type_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

在MoviesController中,我试图获取一些电影以及与用户的关系以及关系的类型。这是我在电影控制器上调用包含的地方:

$this->Movie->contain(array(
    'Person' => array(
        'order' => array(
            'Person.name'=>'ASC'
        ),
        'Activity'
    ),
    'Country' => array(
        'order'=>array(
            'Country.name'=>'ASC'
        )
    ),
    'User'=>array(
        'conditions'=>array(
            'User.id'=>$this->Session->read('Auth.User.id')
        ),
        'MoviesUser'=>array(
            'RelationType'
        )
    )
));

当我尝试运行此功能时,我会收到消息Model" MoviesUser"与模型" RelationType"。

无关

movies_user的字段是: id,user_id,relation_type_id,rate,comment

relation_types的字段是: id,title

这里是我在RelationType Model上的$ has_many属性:

public $hasMany = array(
    'MoviesUser' => array(
        'className' => 'MoviesUser',
        'foreignKey' => 'relation_type_id',
        'dependent' => false,
        'conditions' => '',
        'fields' => '',
        'order' => '',
        'limit' => '',
        'offset' => '',
        'exclusive' => '',
        'finderQuery' => '',
        'counterQuery' => ''
    )
);

0 个答案:

没有答案