CakePHP从一个habtm返回多个记录

时间:2013-06-05 16:36:41

标签: php mysql cakephp activerecord has-and-belongs-to-many

我在问题和类别之间存在着某种关系。这种关系是相应模型中的标准和设置。我现在有以下问题。在控制器动作中,我有一个包含几个问题id的数组。我想返回与这些问题相关的所有类别。我使用的发现看起来如下。

$case_questions_categories = $this->Category->find('all', array('conditions' => array('OR' => $case_question_id_array)));

    // Here the $case_question_id_array is generated as followed:
    foreach($question['CaseQuestion'] as $case_question) {
        $case_question_id_array[] = "Category.question_id = " . $case_question['id'];
    }

很明显,这不起作用,它会引发以下错误:

Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Category.question_id' in 'where clause'

SQL Query: SELECT `Category`.`id`, `Category`.`name`, `Category`.`slug`, `Category`.`category_order`, `Category`.`created`, `Category`.`modified`, `Category`.`is_deleted` FROM `streetofwalls`.`categories` AS `Category` WHERE `Category`.`question_id` = 182

这是有道理的,因为habtm关系中的连接表未在我生成的查询中引用。如何正确处理habtm关系,以便我可以传递一组问题ID并返回相关类别。

感谢任何提供时间或帮助的人。

1 个答案:

答案 0 :(得分:1)

使用联接

您需要生成的SQL查询类型是:

SELECT 
    categories.* from categories 
JOIN 
    categories_questions ON (categories_questions.category_id = categories.id) 
WHERE 
    categories_questions.question_id IN (list, of, question, ids)

最简单的方法是在查询中使用join键 - 这也是in the documentation

应用于问题中的例子:

$ids = array()
foreach($question['CaseQuestion'] as $q) {
    $ids[] = $q['id'];
}

$this->Category->find('all', array(
    'conditions' => array(
        'CategoriesQuestion.id' => $ids // You do not need an OR
    ),
    'joins' => array(
        array(
            'table' => 'categories_questions',
            'alias' => 'CategoriesQuestion',
            'type' => 'inner',
            'conditions' => array(
                'Category.id = CategoriesQuestion.category_id'
            )
        )
    )
));