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

[eluser]Genki1[/eluser]
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:

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

Code:
$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.)
#2

[eluser]WanWizard[/eluser]
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.

Technically:

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.
#3

[eluser]Genki1[/eluser]
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:

Code:
// Create objects
$u = new User();
$u->get_by_id($userid);

$alarm = new Alarm();
$alarm->get_by_id($alarmid);

// 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


#4

[eluser]WanWizard[/eluser]
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