嗨,大家好我想执行以下查询
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
。请帮帮我们
答案 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();