diff --git a/src/SaveRelationsBehavior.php b/src/SaveRelationsBehavior.php index 95ea4f0..69cf05b 100644 --- a/src/SaveRelationsBehavior.php +++ b/src/SaveRelationsBehavior.php @@ -120,12 +120,24 @@ class SaveRelationsBehavior extends Behavior { /** @var ActiveRecord $modelClass */ $modelClass = $relation->modelClass; - // get the related model foreign keys + // Get the related model foreign keys if (is_array($data)) { $fks = []; - foreach ($relation->link as $relatedAttribute => $modelAttribute) { - if (array_key_exists($relatedAttribute, $data) && !empty($data[$relatedAttribute])) { - $fks[$relatedAttribute] = $data[$relatedAttribute]; + + // Get the right link definition + if ($relation->via instanceof ActiveRecord) { + $viaQuery = $relation->via; + $link = $viaQuery->link; + } elseif (is_array($relation->via)) { + list($viaName, $viaQuery) = $relation->via; + $link = $viaQuery->link; + } else { + $link = $relation->link; + } + + foreach ($link as $relatedAttribute => $modelAttribute) { + if (array_key_exists($modelAttribute, $data) && !empty($data[$modelAttribute])) { + $fks[$modelAttribute] = $data[$modelAttribute]; } } } else { diff --git a/tests/SaveRelationsBehaviorTest.php b/tests/SaveRelationsBehaviorTest.php index 0093743..d0787b9 100644 --- a/tests/SaveRelationsBehaviorTest.php +++ b/tests/SaveRelationsBehaviorTest.php @@ -16,6 +16,7 @@ use tests\models\User; use Yii; use yii\base\Model; use yii\db\Migration; +use yii\helpers\VarDumper; class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase { @@ -257,7 +258,7 @@ class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase $this->assertCount(2, $project->users, 'Project should have 2 users before save'); $project->users = array_merge($project->users, [$user]); // Add new user to the existing list $this->assertCount(3, $project->users, 'Project should have 3 users after assignment'); - $this->assertTrue($project->save(), 'Project could not be saved'); + $this->assertTrue($project->save(), 'Project could not be saved'.VarDumper::dumpAsString($project->errors)); $this->assertCount(3, $project->users, 'Project should have 3 users after save'); }