CDbCriteria在Yii中选择多个表

时间:2014-05-12 11:13:37

标签: yii

我有一个SQL查询,它正常工作:

$sql = "
SELECT P.`name`, P.`price`, P.`year`, P.`slug`, P.`image`, C.`title`, C.`des`
FROM `tbl_category` C, `tbl_products` P
WHERE C.`group_cat` = 1 AND C.`slug` = '/category/".$category."/'
ORDER BY `P.updated_at` DESC
LIMIT 0,".Yii::app()->params['limitPageSizeView']
";
$dbCommand = Yii::app()->db->createCommand($sql);
$data = $dbCommand->queryAll();

现在,我希望将此sql转换为语法CDbCriteria:

$criteria = new CDbCriteria();
$criteria->select = '???';
$criteria->where= '???';
$criteria->condition = '???';
$criteria->order = '???';
$criteria->limit = '???';
$data = ProductsModel::model()->findAll($criteria);
有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

$criteria = new CDbCriteria();
$criteria->select = 'name, price, year, slug, image';

$criteria->order = 'upadated_at';
$criteria->limit = Yii::app()->params['limitPageSizeView'];
$criteria->with = array(
'category' => array(
'together'=>true, 
'select'=>array('title','des'),
'condition'=>"group_cat = 1 AND slug = '/category/".$category."/'"
)
);
$data = ProductsModel::model()->findAll($criteria);

这样做会留下加入,确保你在产品的类别上定义关系,如果你没有关系,你可以添加" ON"条件。