如果我使用模型查询表并且我不想在第二个表中使用模型,如何在yii中连接两个表?

时间:2014-03-22 10:09:23

标签: php mysql yii

嗨,大家好我想执行以下查询

select tbl_workspace.wsName,tbl_cities.cityName  from tbl_workspace JOIN tbl_cities on tbl_cities.id = tbl_workspace.city WHERE active=1;

控制器中的方法如下

public function actionWork(){
        $criteria=new CDbCriteria;
        $criteria->order = 'sorter';
        $criteria->condition = 'active=1';
        $criteria->join= 'LEFT JOIN tbl_cities on tbl_cities.id = `t`.`city`';
                    $workspaceList = Workspace::model()->findAll($criteria);
        $response=array();
        $workspace=array();
        $response['status']='True';
        $response['WorkspaceList']=array();
        if ($workspaceList):            
            foreach ($workspaceList as $row):   
                $workspace['id'] = $row['id'];  
                $workspace['wsName'] = $row['wsName'];
                $workspace['city'] = $row['city'];
                array_push($response['WorkspaceList'],$workspace);
            endforeach;
        endif;      
        echo CJSON::encode($response);
}
tbl_workspace中的

模型已在Workspace模型中定义但我没有使用tbl_cities的任何模型,我想获得此值 tbl_cities.cityName,方法actionWork的主体在控制器中定义,我想查询tbl_cities.cityName对象中的$workspaceList。请帮帮我们

1 个答案:

答案 0 :(得分:1)

您必须在yii中使用Relational Active Record。这非常简单实用:

在models \ WorkspaceList.php中添加:

public function relations() {
        return array(
            'cities0' => array(self::BELONGS_TO, 'Cities', 'city'),
)
}

使用CRUD生成器为城市创建模型。 访问此字段$row->cities0->cityName$row['cities0']->cityName

并在findAll中: Workspace::model()->with('cities0')->findAll();