Many-to-Many relation update

What should happen when m-n relation is updated? For example

// $a->hasManyToMany(..."B"...);
$a = new A();
$b = new B();
$a->bs = array($b);
$a->save();
// Ok, lets say we have a connection in the DB
// However I have to save b manually, otherwise it doesn't work
// Now, what if I do this
$b2 = new B();
$a->bs = array($b2);
$a->save();

What I expect to happen: remove a-b connection, b itself remains in the DB, b2 is created in DB with the new link a-b2. What really happens: a now has 2 connections, to b and b2

Is this a bug, or do I need to remove it myself? What is the best way to "disconnect" A and B entries?



82.2k

Connections are get as shared from the di, so every model use the same connection no matter how many saves you do.



7.6k

Either you didn't quite understand my question, or I didn't understand the answer. What I'm talking about is: list of related objects is not updated, new objects are added, old are not removed. E.g. I want to update posts' tags in a blog. ```php $post->tags = $oldTags; $post->save(); $post->tags = $newTags; $post->save(); ``` What I receive at the and is both, old and new tags, when I would like to only have new! Am I wrong with such expectations?



700

Some case here.



7.6k

Well, I ended up using this:

$a->hasManyToMany("..B..");
$a->hasMany("..AtoB..");

$this->db->begin(); // for transaction
$a->AtoB->delete(); // remove connection
$a->B = array(new B(), new B());
$this->db->commit();

So, I define relation to middle-model and remove all of them prior to saving new ones. Don't forget to use transaction, so that if saving related entities fails you can rollback to your old a-to-b connections.



55
edited Dec '15

hi. when phalcon automaticaly add data to middle-model on adding data why did not correct them on update? is this a bug? i have this problem. i think all solutions for this case are not very clean. all of them are solving a case temporary.