Skip to content

Implement hasOne() relationship ID binding.#61

Merged
DarkSide666 merged 6 commits intodevelopfrom
feature/hasone-populate-id-on-save
Jul 21, 2016
Merged

Implement hasOne() relationship ID binding.#61
DarkSide666 merged 6 commits intodevelopfrom
feature/hasone-populate-id-on-save

Conversation

@romaninsh
Copy link
Copy Markdown
Member

When populating model that contains hasOne() relation, sometimes you want to also populate the related entity. This should nicely place the ID of a new record into the main table:

$m = new Model_User($db);

$m['name'] = 'John';
$m->ref('address_id')->save(['address'=>'street']);
$m->save();

This should also save $m['address_id'];

Comment thread src/Field_One.php
if ($this->their_field) {
return $m->loadBy($this->their_field, $this->owner[$this->our_field]);
return $m->tryLoadBy($this->their_field, $this->owner[$this->our_field])
->addHook('afterSave', function ($m) {
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need afterSave hook here even if referenced model can be loaded? This is good if we allow to change id of model, but ... do we allow that?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is a very good point. I'm not sure which one is better.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think agile/data supports changing model id. Can we do:

$m->load(1);
$m['id'] = 2;
$m->save(); // update table set id=2 where id=1 ??? do this work or will create insert instead?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK, i think i want to keep as-is for the following pattern:

$user->ref('contact_id')->load(123)->save();

which allows to easily update to a different record.

@DarkSide666 DarkSide666 merged commit 778cbc7 into develop Jul 21, 2016
@DarkSide666 DarkSide666 deleted the feature/hasone-populate-id-on-save branch July 21, 2016 22:16
@romaninsh romaninsh restored the feature/hasone-populate-id-on-save branch August 19, 2016 10:22
@romaninsh romaninsh deleted the feature/hasone-populate-id-on-save branch August 19, 2016 10:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants