Browse Source

Fixed: Issue #13

tags/1.1.3^0 1.1.3
Alban Jubert 8 years ago
parent
commit
73fc64d24e
  1. 20
      src/SaveRelationsBehavior.php
  2. 3
      tests/SaveRelationsBehaviorTest.php

20
src/SaveRelationsBehavior.php

@ -120,12 +120,24 @@ class SaveRelationsBehavior extends Behavior
{ {
/** @var ActiveRecord $modelClass */ /** @var ActiveRecord $modelClass */
$modelClass = $relation->modelClass; $modelClass = $relation->modelClass;
// get the related model foreign keys // Get the related model foreign keys
if (is_array($data)) { if (is_array($data)) {
$fks = []; $fks = [];
foreach ($relation->link as $relatedAttribute => $modelAttribute) {
if (array_key_exists($relatedAttribute, $data) && !empty($data[$relatedAttribute])) { // Get the right link definition
$fks[$relatedAttribute] = $data[$relatedAttribute]; 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 { } else {

3
tests/SaveRelationsBehaviorTest.php

@ -16,6 +16,7 @@ use tests\models\User;
use Yii; use Yii;
use yii\base\Model; use yii\base\Model;
use yii\db\Migration; use yii\db\Migration;
use yii\helpers\VarDumper;
class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase 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'); $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 $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->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'); $this->assertCount(3, $project->users, 'Project should have 3 users after save');
} }

Loading…
Cancel
Save