Fix setOrCreateRelation - #245
Open
Seb-C wants to merge 1 commit into
Open
Conversation
Collaborator
|
Wow, this method is ugly and hard to understand ! However it seems that neither the old code nor your code are correct. In the old code the related object was never created but in the new code it is always created. Just to illustrate the mess in this method :
😓 |
Collaborator
|
This code should work : protected function &setOrCreateRelation($name, $value)
{
$arr_name = explode('->', $name);
$obj = $this;
foreach ($arr_name as $val_name) {
$rel = $obj->relations($val_name);
if (!empty($rel)) {
// Gets the existing related item
$related = &$obj->get($val_name);
if (empty($related)) {
// No existing related item, creates a new one
$model_to = $rel->model_to;
$related = $model_to::forge();
if ($rel->singular) {
$obj->{$val_name} = $related;
} else {
$obj->{$val_name}[] = $related;
}
}
$obj = $related;
} else if (array_key_exists($val_name, $obj::properties())) {
$obj->set($val_name, $value);
} else {
throw new \Exception('Property or relation `'.$val_name.'` does not exists on model `'.get_class($obj).'`');
}
}
return $obj;
} |
jguyomard
force-pushed
the
master/elche
branch
from
December 5, 2016 09:58
b52d845 to
9631c5f
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
I'm not sure wether or not this may be a breaking change (in that case it's for a future version), but this part of the code is wrong and can never succeed. It causes crashes in some cases for example when trying to save a sub-field from a has-one relation in a crud.
The line
$obj->{$val_name}can't succeed because it's inside anif (empty($obj)).