Skip to content

Commit

Permalink
Prefix attribute with table name in SoftDeleteQueryBehavior methods (…
Browse files Browse the repository at this point in the history
…deleted and unDeleted); Fix #2
  • Loading branch information
elvenpath committed Sep 18, 2016
1 parent c4d8850 commit 6e65068
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 7 deletions.
20 changes: 14 additions & 6 deletions src/SoftDeleteQueryBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

use yii\base\Behavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;

/**
* SoftDeleteQueryBehavior
Expand All @@ -36,19 +37,26 @@ class SoftDeleteQueryBehavior extends Behavior
public $attribute = 'deleted_at';

/**
* @return static
* @return ActiveQuery
*/
public function deleted()
{
return $this->owner->andWhere($this->attribute . ' IS NOT NULL');
/** @var ActiveRecord $modelClass */
$modelClass = $this->owner->modelClass;
$tableName = $modelClass::tableName();

return $this->owner->andWhere($tableName.'.'.$this->attribute.' IS NOT NULL');
}

/**
* @return static
* @return ActiveQuery
*/
public function notDeleted()
{
return $this->owner->andWhere($this->attribute . ' IS NULL');
}
/** @var ActiveRecord $modelClass */
$modelClass = $this->owner->modelClass;
$tableName = $modelClass::tableName();

}
return $this->owner->andWhere($tableName.'.'.$this->attribute.' IS NULL');
}
}
15 changes: 14 additions & 1 deletion tests/unit/SoftDeleteQueryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,4 +43,17 @@ public function testFindNotDeletedPosts()
$this->assertEquals(require(__DIR__ . '/data/test-find-not-deleted-posts.php'), $data);
}

}
/**
* Find Not Deleted Posts
*/
public function testFindNotDeletedPostsWithJoin()
{
$data = [];
$posts = PostA::find()->notDeleted()->joinWith('postB')->all();
foreach ($posts as $post) {
$data[] = $post->toArray();
}
$this->assertEquals(require(__DIR__ . '/data/test-find-not-deleted-posts.php'), $data);
}

}
9 changes: 9 additions & 0 deletions tests/unit/models/PostA.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

namespace tests\models;

use common\models\ProductQuery;
use cornernote\softdelete\SoftDeleteBehavior;
use yii\db\ActiveRecord;

Expand Down Expand Up @@ -47,4 +48,12 @@ public static function find()
{
return new PostQuery(get_called_class());
}

/**
* @return \yii\db\ActiveQuery|ProductQuery
*/
public function getPostB()
{
return $this->hasOne(PostB::className(), ['id' => 'id']);
}
}
7 changes: 7 additions & 0 deletions tests/unit/models/PostB.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,4 +45,11 @@ public function behaviors()
];
}

/**
* @return \yii\db\ActiveQuery|ProductQuery
*/
public function getPostA()
{
return $this->hasOne(PostA::className(), ['id' => 'id']);
}
}

0 comments on commit 6e65068

Please sign in to comment.