douzhonglong3789 2010-03-07 11:24
浏览 38
已采纳

在CakePHP中使HABTM关系独特

I have two models, called Book and Tag, which are in a HABTM relationship. I want a couple (book, tag) to be saved only once. In my models I have

var $hasAndBelongsToMany = array(
    'Tag' => array(
        'className' => 'Tag',
        'joinTable' => 'books_tags',
        'foreignKey' => 'book_id',
        'associationForeignKey' => 'tag_id',
        'unique' => true
    )
);

and viceversa, but the Unique flag does not help me; I can still save two times the same couple.

How do I do this in CakePHP? Should I declare the couple (book, tag) unique in the database directly, or will this make CakePHP go nuts? Is there a Cakey way to handle this situation?

EDIT: I tried making the couple unique with the query (I'm using MySQL)

ALTER TABLE books_tags ADD UNIQUE (book_id,tag_id);

but this does not work well. When I save more than one tag at a time, everything goes well if all the couples are new. If at least one of the couples is repeated, CakePHP fails to do the whole operation, so it does not save ANY new couple (not even the good ones).

  • 写回答

4条回答 默认 最新

  • du31992 2010-03-08 02:09
    关注

    The way Cake usually saves HABTM data is by erasing all existing data for the model from the HABTM table and inserting all the relationships anew from the data array you feed into save(). If you're exclusively using this way to deal with HABTM relationship, you shouldn't have a problem.

    Of course, that's not always the ideal way. To enforce validation on the HABTM table, you need to create the model for it and add some custom validation, like this:

    class BooksTag extends AppModel {
    
        var $validate = array(
            'book_id' => array('rule' => 'uniqueCombi'),
            'tag_id'  => array('rule' => 'uniqueCombi')
        );
    
        function uniqueCombi() {
            $combi = array(
                "{$this->alias}.book_id" => $this->data[$this->alias]['book_id'],
                "{$this->alias}.tag_id"  => $this->data[$this->alias]['tag_id']
            );
            return $this->isUnique($combi, false);
        }
    
    }
    

    Just make sure to save data using saveAll($data, array('validate' => 'first')) to trigger the validation.

    You may have to specify the BooksTag model explicitly in the relationship:

    var $hasAndBelongsToMany = array(
        'Tag' => array(
            ...
            'with' => 'BooksTag'
        )
    );
    

    If on top of that you're also enforcing the uniqueness on the DB level, all the better.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效