2016-07-19 47 views
0

我有3个表Yii2:ActiveQuery使用关系

证书,用户状态

他们有这些关系:

certificates - user, one -- many 
user-status, one -- one 

我有activeQuery太:

$this->andWhere(['<', 'created', new Expression("DATE_SUB(NOW(), INTERVAL " . $days . " DAY)")]) 
      ->andWhere(['is_active' => 1]) 
      ->andWhere(['<', 'delayed_until', new Expression("NOW()")]) 
      ->andWhere(['<', 'resend_count', LeCertificate::RESEND_COUNT]) 

是有可能添加范围->andWhere我可以得到status.not_deleted = 0当前证书?

回答

1

假设你已经在LeCerificateUser类中定义的正确关系:

LeCertificate::find()->alias('C') 
    ->joinWith(['users', 'users.status S'], false, 'INNER JOIN') 
    ->andWhere(['<', 'C.created', new Expression("DATE_SUB(NOW(), INTERVAL " . $days . " DAY)")]) 
    ->andWhere(['C.is_active' => 1]) 
    ->andWhere(['<', 'C.delayed_until', new Expression("NOW()")]) 
    ->andWhere(['<', 'C.resend_count', LeCertificate::RESEND_COUNT]) 
    ->andWhere(['S.not_deleted' => 0]); 

关系应该看起来像如下:

class LeCertificate extends ActiveRecord 
{ 
    ... 

    public function getUsers() 
    { 
     return $this->hasMany(User::className(), ['certificate_id' => 'id']); 
    } 

    ... 
} 

class User extends ActiveRecord 
{ 
    ... 

    public function getStatus() 
    { 
     return $this->hasOne(Status::className(), ['id' => 'status_id']); 
    } 

    ... 
}