0

我在以 Yii 面向模型的风格编写此查询时遇到了问题。

我有 3 个主表:问题、类别、国家和关系表:questions_has_categories、questions_has_countries。

现在我尝试搜索属于国家、类别的问题。

使用普通的 SQL 语句,我写:

SELECT q.id, q.question, c.name, co.name
                FROM questions AS q, 
                     categories AS c, 
                     countries AS co,
                     questions_has_countries AS ta,
                     questions_has_categories AS qhc

                WHERE 
                     q.id = qhc.questions_id
                AND  c.id = qhc.categories_id
                AND  q.id = ta.questions_id 
                AND  co.id = ta.countries_id
                AND  c.id = 1 
                AND  co.id = 2

这工作正常。现在使用 Yii Active Record 我尝试像这样搜索:

$model = Questions::model()->with( 
         array( 'categories' => array (
                     'select' => 'name',
                     'condition' => 'categories.id=:cat_id',
                     'params' => array (':cat_id' => $_POST["Questions"]["categories"])
                     ) 
              ), 
         array( 'countries' => array (
                     'select' => 'name',
                     'condition' => 'countries.id=:cou_id',
                     'params' => array (':cou_id' => $_POST["Questions"]["countries"])
                     ) 
        )
)->findAll(array ('select' => 'question'));

此代码仅尊重类别,而不是国家(返回所有国家,不过滤,缩小范围)。

我究竟做错了什么 ?

我的问题模型关系函数如下所示:

public function relations()
{
return array('categories' => array(self::MANY_MANY, 'Categories',  'questions_has_categories(questions_id, categories_id)'),
             'countries' => array(self::MANY_MANY, 'Countries', 'questions_has_countries(questions_id, countries_id)'),
    );
}

请帮助:)谢谢

4

1 回答 1

1

尝试这个

$model = Questions::model()->with( 
             array( 'categories' => array (
                      'select' => 'name',
                      'condition' => 'categories.id=:cat_id',
                      'params' => array (':cat_id' => $_POST["Questions"]["categories"])
                    ),
                    'countries' => array (
                      'select' => 'name',
                      'condition' => 'countries.id=:cou_id',
                      'params' => array (':cou_id' => $_POST["Questions"]["countries"])
                    ) 
                  )
    )->findAll(array ('select' => 'question'));
于 2013-09-12T14:19:24.887 回答