Skip to content

Commit

Permalink
Fixes #1 by correcting appending for belongs_to
Browse files Browse the repository at this point in the history
  • Loading branch information
louismrose committed Sep 23, 2016
1 parent 20a02d0 commit 99b0333
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
9 changes: 9 additions & 0 deletions lib/Relationship.php
Original file line number Diff line number Diff line change
Expand Up @@ -676,5 +676,14 @@ 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;
}
};
?>
8 changes: 8 additions & 0 deletions test/RelationshipTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,14 @@ 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_belongs_to_can_be_self_referential()
{
Author::$belongs_to = array(array('parent_author', 'class_name' => 'Author', 'foreign_key' => 'parent_author_id'));
Expand Down

0 comments on commit 99b0333

Please sign in to comment.