【发布时间】:2015-10-07 16:01:20
【问题描述】:
我正在做一个项目,我有自己的 ActiveRecord 类,该类扩展 \yii\db\ActiveRecord:
class ActiveRecord extends \yii\db\ActiveRecord
{
const DELETED_STATUS = 1;
/**
* Defines the soft delete field
*/
public static function softDeleteField()
{
return 'Deleted';
}
/**
* Overrides the find() function to add sensitivity to deletes
*/
public static function find()
{
return parent::find()->where(['not',[
static::softDeleteField() => static::DELETED_STATUS
]]);
}
}
我希望能够使所有内容都可以软删除。根据documentation,应用这样的默认条件应该是可行的。
它在大多数情况下工作得很好,但是当我尝试进行连接时,我得到一个 sql 错误。这方面的一个例子是:
$query = Model::find(); // ActiveRecord of table1
$query->joinWith(['alias' => function($query) { $query->from(['alias' => 'table2']); }]);
我得到了错误:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'Deleted' in where clause is ambiguous
The SQL being executed was: SELECT COUNT(*) FROM `table1` LEFT JOIN `table2` `alias` ON `table1`.`StatusID` = `alias`.`StatusID` WHERE (NOT (`Deleted`=1)) AND (NOT (`Deleted`=1))
我能够通过将我的联接查询更改为
来使其工作// Omitting the alias in the from() method
$query->joinWith(['alias' => function($query) { $query->from('table2'); }]);
并将我的 find() 方法更改为
public static function find()
{
return parent::find()->where(['not',[
static::tableName()."."static::softDeleteField() => static::DELETED_STATUS
]]);
}
但这只有在没有别名的情况下才有效。我可以做些什么来使这个工作也适用于带有别名的连接查询吗?
【问题讨论】:
标签: mysql activerecord yii2