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条)

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源