Skip to content

Commit

Permalink
Corrects record appending for belongs_to jpfuentes2#546
Browse files Browse the repository at this point in the history
  • Loading branch information
louismrose committed Jul 5, 2016
1 parent f56c77e commit c67ee20
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/Relationship.php
Original file line number Diff line number Diff line change
Expand Up @@ -725,4 +725,13 @@ public function load_eagerly($models=array(), $attributes, $includes, Table $tab
{
$this->query_and_attach_related_models_eagerly($table,$models,$attributes,$includes, $this->primary_key,$this->foreign_key);
}
}

// Unlike the other relationships, a belongs_to stores its foreign key on the associate (and not
// on the new record). Therewfore, we must override the append_record_to_associate behaviour of
// AbstractRelationship to provide this behaviour.
protected function append_record_to_associate(Model $associate, Model $record)
{
$associate->{$this->foreign_key[0]} = $record->id;
return $record;
}
}
9 changes: 9 additions & 0 deletions test/RelationshipTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,15 @@ public function test_belongs_to_create_association()
$this->assert_not_null($venue->id);
}

public function test_belongs_to_create_association_sets_foreign_key()
{
$event = $this->get_relationship();
$values = array('city' => 'Richmond', 'state' => 'VA', 'name' => 'Club 54', 'address' => '123 street');
$venue = $event->create_venue($values);

$this->assert_equals($venue->id, $event->venue_id);
}

public function test_build_association_overwrites_guarded_foreign_keys()
{
$author = new AuthorAttrAccessible();
Expand Down

0 comments on commit c67ee20

Please sign in to comment.