0

I try to add a Tag system to my Website.

Users can create Tickets and add Tags to them.

To do this I have a HABTM relation between the Models Ticket and Tag.

My problem is now:

When I save a new relation I can have multiple Times the same Ticket id in the tags_tickets table, but as soon as I try to use the tag_id more than once it deletes the old entries for this id.

class Tag extends AppModel {
public $name = 'Tag';
public $actsAs = array('Containable');

public $hasAndBelongsToMany = array(
        'Ticket' => array(
                'className'              => 'Ticket',
                'joinTable'              => 'tags_tickets',
                'foreignKey'             => 'tag_id',
                'associationForeignKey'  => 'ticket_id',
                'unique'                 => 'keepExisting',
        )
);
}

class Ticket extends AppModel {
public $name = 'Ticket';
public $actsAs = array('Containable');

    public $hasAndBelongsToMany = array(
        'Tag' => array(
                'className'              => 'Tag',
                'joinTable'              => 'tags_tickets',
                'foreignKey'             => 'ticket_id',
                'associationForeignKey'  => 'tag_id',
                'unique'                 => 'keepExisting',
        )
);
}

In the function of the controller I do a saveAll.

Just an example of what i mean:

ticket.id = 1 and tag_id = 1 works just fine.

I can now add for example ticket.id = 1 and tag_id = 2.

But when I add ticket.id = 2 and tag_id = 1 it deletes the entry with ticket.id = 1 and tag_id = 1.

I can't get it to work properly. I don't want to change unique to false because I don't want to have multiple times the same relation in the database. Is there a way to solve this?

Coltaine
  • 1
  • 1

2 Answers2

0

you should spend a bit of time reading the docs

Specifically look at the configuration options available, such as unique

dogmatic69
  • 7,574
  • 4
  • 31
  • 49
  • This is what i mean. When I use unique = false it works fine but i can have double entries. This is something i would like to prevent. It should work with 'keepExisting' but it still deletes the other entries. It only should delete exactly the same ones. – Coltaine Jun 26 '13 at 10:02
  • Seems like you have the wrong model loaded or wrong version of cake. There are tests for this showing it to work. – dogmatic69 Jun 26 '13 at 14:13
  • Maybe, but I tried multiple solutions now without any success. The only thing which works fine now is the solution I posted above. – Coltaine Jun 28 '13 at 06:07
0

I solved the problem with a workaround:

I created a separate Model for the tags_tickets table (TagTicket) and removed the HABTM associations in the Ticket and Tag Model.

For that I added for the Ticket and Tag Model a hasMany relation with TagTicket Model and this Model got a belongsTo relation to Ticket and Tag.

Now I can save and delete as I wish and can check for duplicates before save.

Coltaine
  • 1
  • 1