Search code examples
codeigniterrelationshipscodeigniter-datamapper

CodeIgniter/Datamapper - updating one-to-many relationships


Having an issue with update one-to-many relationships with CodeIgniter/Datamapper. In my mind I had the notion that when a one-to-many relationship was updated. The existing records within the relationship table would be removed and the new relationships added. This appears not to be the case.

Using the following, adds new records to the relationship table each time:

$item->save($banners);

The relationships that are created are correct but I was expecting only the objects contained within $banners to be included in the relationship table not any historial items.

Is this correct functionality and if so what is the best method for making this update process work?

Thanks


Solution

  • One-to-many doesn't mean "only one can be related". See Wikipedia

    It just means that the "one" side of the relationship contains the foreign key.

    You need to manually reset existing relations if you want this behaviour. This goes quickest using an update query where you set 'foreign_key' to NULL where 'foreign_key' is the 'id' value of the object to be related.