2

I'm using codeigniter 2.1.4 & datamapper orm. I know how to save relations to an object and I know how to delete them.

In this case I have a many-to-many relation, which I want to update with new values from a form. Now I can use this to save them which works just fine:

$ousergroupright = new Usergroupright;
$usergrouprights = $ousergroupright->where_in('id', $this->input->post('usergrouprights'))->get();

$ousergroup = new Usergroup;
$ousergroup->get_by_id($id);
$ousergroup->save($usergrouprights->all);

But this doesn't delete the records I "unchecked" in my form. I need to delete the objects I don't want related anymore. What would be the best way to do this (without using custom queries)?

A query like above with $ousergroup->where_not_in() before saving seems overkill to me (why query database and build objects just to delete a relation?):

$ousergroupright = new Usergroupright;
$usergrouprights = $ousergroupright->where_not_in('id', $this->input->post('usergrouprights'))->get();

$ousergroup = new Usergroup;
$ousergroup->get_by_id($id);
$ousergroup->delete($usergrouprights->all);

Any ideas?

Wietse
  • 372
  • 7
  • 18

1 Answers1

0

There is a way to delete the objects you don't want related anymore without the need to query a database and build objects just to delete a relation. You can use the utility function query a run a custom SQL to delete all the unrelated objects WITHOUT needing to perform a database query, something like:

// Create usergroup object
$u = new Usergroup();

// your custom SQL query to delete the unrelated objects
$sql = "delete from usergrouprights where usergroup.id = ? and id usergrouprights.id not in (?)";

// Binding values
$binds = array($idUserGroup , $listOfSelectedItens);

// Run query to populate user object with the results
$u->query($sql);

More about DataMapper query utility function http://datamapper.wanwizard.eu/pages/utility.html#query

  • Using a custom query is a nice solution, but I would like to use the model. When I change the properties of the model, I don't want to search my application for "custom queries"... – Wietse Apr 18 '14 at 08:00
  • Well, in this case, i think you could have been more specific about that in your question but okay, i can understand that you dont want to use custom queries – bovino Marcelo Bezerra Apr 18 '14 at 14:41
  • 1
    Thanks for your answer Marcelo, but I think my option (select all where !=...) and yours (custom queries) both aren't the solution I'm looking for. There has to be another (better) way! – Wietse Apr 23 '14 at 18:52