2016-03-25 54 views
0

在公司模型中,我加入了模型user和business_unit。如何獲取YII中CDbCriteria的連接屬性?

$criteria=new CDbCriteria; 
$criteria->compare('id',$this->id); 
$criteria->compare('status',$this->status); 

$criteria->condition = "`t`.status = '1'"; 
$criteria->order = 'created DESC'; 
$criteria->join = " inner join users on users.company_id = `t`.id"; 

$criteria->condition = "`t`.status = '1'"; 
$criteria->order = 'created DESC'; 
$criteria->join = " inner join business_unit on business_unit.company_id = `t`.id"; 

它的工作原理。但我得到的只有公司attributes.How我得到business_unitusers屬性以及屬性company

回答

1

你應該創建「公司」模型關係,爲用戶和business_unit,如:

1)的第一件事就是到檢查您是否已經在公司的模型兩個關係,爲用戶和business_unit:

public function relations() 
{ 
    return array(
     'users' => array(self::HAS_MANY, 'User', 'company_id'), 
     'businessUnits' => array(self::HAS_MANY, 'BusinessUnit', 'company_id'), 
    ); 
} 

2)然後,您可以創建標準:

$criteria=new CDbCriteria; 
$criteria->compare('id',$this->id); 
$criteria->compare('status',$this->status); 
$criteria->with = array('users', 'businessUnits'); 
$criteria->together = true; 

3)把所有型號:

$models = Company::model()->findAll($criteria); 

那麼對你來說有每個模型的用戶和業務單位:

foreach($models as $m) 
{ 
    // Users 
    $users = $m->users; 
    $bu = $m->businessUnit; 
} 

4)有活動數據提供:

$dataProvider = new CActiveDataProvider('Company', array('criteria' => $criteria); 
+0

謝謝它的工作原理...更多的事情是如何獲得嵌套連接屬性 –

+0

在foreach循環每個關係(因爲關係是has_many) –