Welcome Guest, Not a member yet? Register   Sign In
DataMapper: does set_join_field() create a new record or only update an existing one?

Hi WanWizard,

When using set_join_field(), it seems to only update the join table if the two records have already been related with a save(). Is that correct?

After doing this, the join table has the expected new record:

$u = new User(1);
$b = new Book(99);
$u->set_join_field($b, 'value', TRUE);
After doing this, the join table does not contain the expected record:

$u = new User(1);
$b = new Book(99);
$u->set_join_field($b, 'value', TRUE);

The relationships have been properly defined in the models.
Is the behavior I'm encountering correct?

(BTW, the manual for set_join_field() does not explicitly state whether a save() must be issued after set_join_field(). I checked the library and see that the update is performed, but it would be helpful to state so in the documentation.)

That is correct.

As long as the relation isn't created, there is no relation record in the join table, and therefore nothing to set.


It will do an "UPDATE books_users SET value = 1 WHERE book_id = 99 AND user_id = 1" which will update 0 records as that combination of keys does not exist yet.

Thank you for confirming. For the benefit of others, here is the example from the manual (http://datamapper.wanwizard.eu/pages/joinfields.html) with my notes added:

// Create objects
$u = new User();

$alarm = new Alarm();

// relate the objects
$u->save($alarm);  // needed once only, not each time set_join_field() is called

// mark this alarm as fired
$alarm->set_join_field($u, 'wasfired', TRUE);  
// table has been updated; save() is not needed

I've had this question several times as I've started and stopped development and need to refresh my understanding of DM. It would be helpful if the example in the documentation noted:
(a) the need to establish the relationship before using set_join_field(), and
(b) no need for a save() after set_join_field()

Thanks again


I've added a note about the two objects being related before using set_join_field() to the docs, for inclusion in the next version.

Theme © iAndrew 2016 - Forum software by © MyBB