diff --git a/lib/Relationship.php b/lib/Relationship.php index 2b8144898..689507de1 100644 --- a/lib/Relationship.php +++ b/lib/Relationship.php @@ -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; + } }; ?> diff --git a/test/RelationshipTest.php b/test/RelationshipTest.php index 6f428ac1a..047d18130 100644 --- a/test/RelationshipTest.php +++ b/test/RelationshipTest.php @@ -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'));