diff --git a/composer.json b/composer.json index 4d58920..54a28ec 100755 --- a/composer.json +++ b/composer.json @@ -1,7 +1,7 @@ { "name": "sjdaws/vocal", "description": "Extended functionality for Eloquent in Laravel 4.1+", - "version": "0.2.4", + "version": "0.2.5", "type": "library", "license": "MIT", "keywords": ["laravel", "eloquent", "orm", "activerecord", "recursive", "hydration", "validation", "angular", "angularjs"], diff --git a/src/Sjdaws/Vocal/Vocal.php b/src/Sjdaws/Vocal/Vocal.php index 8b15848..995ee6e 100755 --- a/src/Sjdaws/Vocal/Vocal.php +++ b/src/Sjdaws/Vocal/Vocal.php @@ -782,7 +782,12 @@ private function saveRelations($conditions, $rules, $messages, $relationships, $ // Save record on success, log errors on fail if ($result) { - if (method_exists($this->$modelClass(), 'associate')) $this->$modelClass()->associate($record)->forceSave(); + if (method_exists($this->$modelClass(), 'associate')) { + + // we must save the record first before associating it + $record->forceSave(); + $this->$modelClass()->associate($record)->forceSave(); + } else { $result = $this->$modelClass()->saveRelation($record); diff --git a/tests/Migrations/2014_04_02_090800_create_test_child_table.php b/tests/Migrations/2014_04_02_090800_create_test_child_table.php index 1b1906d..3b2037b 100755 --- a/tests/Migrations/2014_04_02_090800_create_test_child_table.php +++ b/tests/Migrations/2014_04_02_090800_create_test_child_table.php @@ -22,7 +22,7 @@ public function up() Schema::create($this->table, function($t) { $t->increments('id')->unsigned(); - $t->integer('test_id')->unsigned(); + $t->integer('test_id')->unsigned()->nullable(); $t->string('description', 100); $t->timestamps(); }); diff --git a/tests/VocalTest.php b/tests/VocalTest.php index b26fd05..803f963 100755 --- a/tests/VocalTest.php +++ b/tests/VocalTest.php @@ -156,5 +156,22 @@ public function testVocal() $this->assertTrue($result, $this->errorResponse('Record was not saved', $test)); $this->assertTrue($test->password && $test->password != $input->get('password'), $this->errorResponse('Record was not saved', $test)); + + // Test that the inverse relationship (belongsTo) works + $input->replace(array( + 'description' => 'Child 3', + 'parent' => array( + 'description' => 'Parent 2', + ) + )); + + $child = new TestChild; + $result = $child->saveRecursive(); + + // Make sure validation passed + $this->assertTrue($result, $this->errorResponse('Record was not saved', $child)); + + // Make sure the parent has an ID (that means it was actually saved) + $this->assertTrue(!!$child->parent->id, true); } }