如何在 YII 中获取 CDbCriteria 中的连接属性?

How to get join attributes in CDbCriteria in YII?

在公司模型中,我加入了模型用户和 business_unit。

$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 属性

您应该在 "company" 模型中为用户和 business_unit 创建关系,例如:

1)首先要检查公司模型中是否有这两个关系,for users and 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);