与蛋糕中的HABTM混淆

时间:2012-08-24 15:41:08

标签: php cakephp-2.0 cakephp-appmodel

我有3个表格结构......

SONG (身份,状态)

TRACKLIST (id,song_id,artist_id,status)

艺术家(身份,状态)

我希望HABTM所以我提到了...... 歌曲模型

var $hasAndBelongsToMany = array(
    'Artist' => array(
        'className' => 'Artist',
        'joinTable' => 'tracklists',
        'foreignKey' => 'song_id',
        'associationForeignKey' => 'artist_id',
        'conditions' => array('tracklist.status' => '1')
    'with' => 'Tracklist',
    //'unique' => true
    ),
);

艺术家模型

 var $hasAndBelongsToMany = array(
    'Song' => array(
        'className' => 'Song',
        'joinTable' => 'tracklists',
        'foreignKey' => 'artist_id',
        'associationForeignKey' => 'song_id',
        'with' => 'Tracklist',
        //'unique' => true
    ),
);

Tracklist模型     var $ belongsTo = array(

    'Song' => array(
        'className' => 'Song',
        'foreignKey' => 'song_id',
        'dependent' => true
    ),
    'Artist' => array(
        'className' => 'Artist',
        'foreignKey' => 'artist_id',
        'dependent' => true
    )
);

这种方式但问题是,当我试图从Artist表中查找记录时,它找到了没有任何条件的所有记录。

    $artist_conditions = array('Artist.status' => '1');
    $artist_list = $this->Song->Artist->find('list', array('conditions' => $artist_conditions ));

我希望只获取与该曲目列表相关的艺术家,并将tracklist.status设为1。这种关系是否正确?或者我只使用hasMany(Song,Artist)和BelongsTo(Tracklist)。

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

/* for example in songs controller */
    public $uses = array('Song','Tracklist');
    $artist_conditions = array('Artist.status' => '1');
    $this->Tracklist->recursive = 1;
    $artist_list = $this->Tracklist->find('list', array('conditions' => $artist_conditions ));