Yii 如何在关系模型中设置条件
我有两个名为Yii 如何在关系模型中设置条件,yii,get,many-to-many,Yii,Get,Many To Many,我有两个名为content和category的表,它们有MANY\u MANY这样的关系: 'contents'=>array(self::MANY_MANY, 'Content', 'content_category(category_id, content_id)', 'order'=>'contents.id DESC', ) $category = Category::model()->findB
content
和category
的表,它们有MANY\u MANY
这样的关系:
'contents'=>array(self::MANY_MANY, 'Content',
'content_category(category_id, content_id)',
'order'=>'contents.id DESC',
)
$category = Category::model()->findByPk($cat_id);
foreach ($category->contents as $content)
{
//some code for each content
}
content_category是这两个表之间的中间表。因此,我使用这个关系来查找一个类别的内容,如下所示:
'contents'=>array(self::MANY_MANY, 'Content',
'content_category(category_id, content_id)',
'order'=>'contents.id DESC',
)
$category = Category::model()->findByPk($cat_id);
foreach ($category->contents as $content)
{
//some code for each content
}
现在我想为content
table写一些不相关的条件,以便,这个关系找到一些内容。我的情况可能是多种多样的,从$\u get
变量中获取它们。
我必须如何写我的条件你应该使用CDbCriteria来写。下面是一个简单的例子:
$criteria = new CDbCriteria;
$criteria->select = 'the columns you need';
$criteria->limit = 5; // the number of row to fetch
$criteria->condition = 'column=:param OR column2="example"';
$criteria->params = array(':param' => $_GET['param'];//bind the param to the condition
//here I am going to add some conditions about the related model
$criteria->with = array(
'content' => array(
'select' => 'the columns you need in the related model',
'condition' => 'column=:param',
'params' => array(':param' => $_GET['param']),
),
);
$category = Category::model()->findAll($criteria);
阅读Yii文档,了解更多选项。也有一些例子你有没有试着看一下?您也可以尝试阅读文档。一切都在那里。