Browse Source

Merge 1.3.2 release

tags/1.4.0
Alban Jubert 7 years ago
parent
commit
689be49f9f
  1. 4
      CHANGELOG.md
  2. 20
      src/SaveRelationsBehavior.php
  3. 37
      tests/SaveRelationsBehaviorTest.php
  4. 48
      tests/models/BadConfigurationModel.php
  5. 23
      tests/models/User.php
  6. 28
      tests/models/UserProfile.php

4
CHANGELOG.md

@ -1,5 +1,9 @@
# Yii2 Active Record Save Relations Behavior Change Log
## [1.3.2]
### Fixed
- Bug #22: Fix for HasOne relation pointing to the owner primary key (thx @mythicallage)
## [1.3.1]
### Added
- Enh #19: Support for defining relations through the `getRelation` method (thx @execut)

20
src/SaveRelationsBehavior.php

@ -253,7 +253,7 @@ class SaveRelationsBehavior extends Behavior
/**
* For each related model, try to save it first.
* If set in the owner model, operation is done in a transactional way so if one of the models should not validate
* or be saved, a rollback will occur.
* or be saved, a rollback will occur.,
* This is done during the before validation process to be able to set the related foreign keys.
* @param BaseActiveRecord $model
* @param ModelEvent $event
@ -261,7 +261,10 @@ class SaveRelationsBehavior extends Behavior
*/
protected function saveRelatedRecords(BaseActiveRecord $model, ModelEvent $event)
{
if (($model->isNewRecord && $model->isTransactional($model::OP_INSERT)) || (!$model->isNewRecord && $model->isTransactional($model::OP_UPDATE)) || $model->isTransactional($model::OP_ALL)) {
if (($model->isNewRecord && $model->isTransactional($model::OP_INSERT))
|| (!$model->isNewRecord && $model->isTransactional($model::OP_UPDATE))
|| $model->isTransactional($model::OP_ALL)
) {
$this->_transaction = $model->getDb()->beginTransaction();
}
try {
@ -270,9 +273,16 @@ class SaveRelationsBehavior extends Behavior
$relation = $model->getRelation($relationName);
if (!empty($model->{$relationName})) {
if ($relation->multiple === false) {
// Save Has one relation new record
$pettyRelationName = Inflector::camel2words($relationName, true);
$this->saveModelRecord($model->{$relationName}, $event, $pettyRelationName, $relationName);
$relationModel = $model->{$relationName};
if (!($model::isPrimaryKey(array_values($relation->link))
&& $relationModel::isPrimaryKey(array_keys($relation->link))
&& $model->getIsNewRecord()
&& $relationModel->getIsNewRecord()
)) {
// Save Has one relation new record
$pettyRelationName = Inflector::camel2words($relationName, true);
$this->saveModelRecord($model->{$relationName}, $event, $pettyRelationName, $relationName);
}
} else {
// Save Has many relations new records
/** @var BaseActiveRecord $relationModel */

37
tests/SaveRelationsBehaviorTest.php

@ -3,7 +3,6 @@
namespace tests;
use lhs\Yii2SaveRelationsBehavior\SaveRelationsBehavior;
use RuntimeException;
use tests\models\Company;
use tests\models\DummyModel;
use tests\models\DummyModelParent;
@ -32,6 +31,7 @@ class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase
$db->createCommand()->dropTable('project_user')->execute();
$db->createCommand()->dropTable('project')->execute();
$db->createCommand()->dropTable('user')->execute();
$db->createCommand()->dropTable('user_profile')->execute();
$db->createCommand()->dropTable('company')->execute();
$db->createCommand()->dropTable('link_type')->execute();
$db->createCommand()->dropTable('link')->execute();
@ -64,6 +64,12 @@ class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase
'username' => $migration->string()->notNull()->unique()
])->execute();
// User profile
$db->createCommand()->createTable('user_profile', [
'user_id' => $migration->primaryKey(),
'bio' => $migration->text(),
])->execute();
// Project
$db->createCommand()->createTable('project', [
'id' => $migration->primaryKey(),
@ -161,20 +167,25 @@ class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase
])->execute();
}
/**
* @expectedException RuntimeException
*/
public function testCannotAttachBehaviorToAnythingButActiveRecord()
{
$this->setExpectedException('RuntimeException');
$model = new Model();
$model->attachBehavior('saveRelated', SaveRelationsBehavior::className());
}
/**
* @expectedException \yii\base\InvalidCallException
*/
public function testUnsupportedRelationProperty()
{
$this->setExpectedException('\yii\base\UnknownPropertyException');
$model = new Project();
$model->detachBehaviors();
$model->attachBehavior('saveRelated', new SaveRelationsBehavior(['relations' => ['links' => ['fakeParam' => 'Some value']]]));
}
public function testTryToSetUndeclaredRelationShouldFail()
{
$this->setExpectedException('\yii\base\InvalidCallException');
$project = new Project();
$project->projectUsers = [];
}
@ -628,4 +639,16 @@ class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase
$this->assertTrue($project->save(), 'Project could not be saved');
}
public function testSaveHasOneWithPrimaryKeyAsForeignKey()
{
$user = new User();
$user->username = 'Dummy More';
$user->userProfile = [
'bio' => "Some great bio"
];
$this->assertTrue($user->save(), 'User could not be saved');
$this->assertEquals($user->userProfile->bio, "Some great bio");
$this->assertEquals($user->id, $user->userProfile->user_id);
}
}

48
tests/models/BadConfigurationModel.php

@ -0,0 +1,48 @@
<?php
/**
* @link http://www.lahautesociete.com
* @copyright Copyright (c) 2016 La Haute Société
*/
namespace tests\models;
use lhs\Yii2SaveRelationsBehavior\SaveRelationsBehavior;
/**
* DummyModel class
*
* @author albanjubert
**/
class BadConfigurationModel extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'dummy';
}
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'saveRelations' => [
'class' => SaveRelationsBehavior::className(),
'relations' => ['children']
],
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getChildren()
{
return $this->hasOne(DummyModel::className(), ['id' => 'parent_id']);
}
}

23
tests/models/User.php

@ -2,6 +2,8 @@
namespace tests\models;
use lhs\Yii2SaveRelationsBehavior\SaveRelationsBehavior;
class User extends \yii\db\ActiveRecord
{
/**
@ -15,6 +17,19 @@ class User extends \yii\db\ActiveRecord
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'saveRelations' => [
'class' => SaveRelationsBehavior::className(),
'relations' => ['userProfile']
],
];
}
/**
* @inheritdoc
*/
public function rules()
{
return [
@ -23,4 +38,12 @@ class User extends \yii\db\ActiveRecord
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUserProfile()
{
return $this->hasOne(UserProfile::className(), ['user_id' => 'id']);
}
}

28
tests/models/UserProfile.php

@ -0,0 +1,28 @@
<?php
namespace tests\models;
class UserProfile extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'user_profile';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['user_id'], 'integer'],
['bio', 'required'],
[['user_id'], 'unique'],
[['user_id'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['user_id' => 'id']]
];
}
}
Loading…
Cancel
Save