Yii2 ActiveRecord - 默认条件导致sql错误

时间:2015-10-07 16:01:20

标签: mysql activerecord yii2

我正在开展一个项目,我有自己的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
        ]]);
    }
}

我希望能够使所有软件都可以删除。根据{{​​3}},应用这样的默认条件应该是可行的。

它在大多数情况下工作得很好,但是当我尝试进行连接时,我得到一个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
    ]]);
}

但这只有在没有别名的情况下才有效。我是否可以做些什么来使用别名连接查询?

2 个答案:

答案 0 :(得分:0)

我认为你应该使用SELF而不是static

像这样

public static function find()
{
    return parent::find()->where(['not',[
        SELF::softDeleteField() => SELF::DELETED_STATUS
    ]]);
}

答案 1 :(得分:0)

错误消息说:许多表都有已删除的字段,您必须澄清在SQL查询中使用的字段。

您必须使用表名或类似

的别名来定义Deleted
/**
 *  Defines the soft delete field
 */
public static function softDeleteField()
{
    return self::tableName() . '.Deleted';
}