Making HABTM relationships unique in CakePHP

Posted by Andrea on Stack Overflow See other posts from Stack Overflow or by Andrea
Published on 2010-03-07T11:24:16Z Indexed on 2010/03/08 2:12 UTC
Read the original article Hit count: 451

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about php

Related posts about cakephp