2015-10-07 43 views
1

我工作的一個項目,我有一個擴展\yii\db\ActiveRecord我自己的ActiveRecord類:Yii2 ActiveRecord的 - 默認情況下會導致SQL錯誤

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 
    ]]); 
} 

但是這隻會在沒有別名的情況下起作用。有什麼我可以做的,以使這個工作的別名連接查詢以及?

回答

0

我認爲你應該使用SELF,而不是static

這樣

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

我能做到這一點,但偶爾也會指示東西是否被刪除的字段是在擴展我的'ActiveRecord'類的類不同,所以我需要使用晚期靜態綁定。 – spencer4of6

0

錯誤消息指出:許多表已經刪除的字段,要弄清你的SQL查詢確實使用哪一個領域。

你必須用表名或別名一樣,定義Deleted

/** 
* Defines the soft delete field 
*/ 
public static function softDeleteField() 
{ 
    return self::tableName() . '.Deleted'; 
} 
+0

你知道一種以編程方式確定表是否被別名化的方法嗎?正如你在我原來的問題中所看到的那樣,我現在正在使用'tableName()'方法,但是如果一個表在別名查詢中被別名,這是行不通的。 – spencer4of6

+1

@ spencer4of6,我想你可能不會在Yii2中使用別名,因爲它對ActiveQuery和SQL builder沒有用處 – Sergey