Fix Many Many relation between more than 2 tables

When you save a model instance that has a many-many relation, this behavior delete all the records in the join table that match the condition "<m2mThisField> = <primary key>" and than update the relation (only partially). The problem subsist when 3 or more tables are involved in the relation. For example:

Suppose that we have 3 tables, Rule, User and Group:
rule(id, ...)
user(id, ...)
group(id, ...)

Each record of Rule involves many users and/or many groups. This relation in the database becomes a table with a reference to the previous three tables:
rule_user_group(id, id_rule, id_user, id_group)

Each record of this table has id_rule always enhanced while id_user and id_group are enhanced in exclusive way (id_user not null and id_group null or vice versa). Suppose we have 2 records:

rule_user_group(1, 100, 200, NULL)           // Join the rule 100 to user 200
rule_user_group(2, 100, NULL, 300)           // Join the rule 100 to group 300

Now if we update the the groups associated to the rule 100:
$model->groups = array(300, 301, 302);     // add group 301 and 302
$model->save();

After save we expect this result:
rule_user_group(1, 100, 200, NULL)
rule_user_group(2, 100, NULL, 300)
rule_user_group(3, 100, NULL, 301)
rule_user_group(4, 100, NULL, 302)

We have instead:
rule_user_group(2, 100, NULL, 300)
rule_user_group(3, 100, NULL, 301)
rule_user_group(4, 100, NULL, 302)

This happens because all the records in rule_user_group with rule_id=100 will be deleted and than the relation will be updated.

In alternative to this fix you can split the join table in many tables how many are the foreign keys:
rule_user(id, id_rule, id_user)
rule_group(id, id_rule, id_group)