CakePHP查找具有相关模型条件的列表

时间:2011-05-16 20:57:43

标签: php mysql cakephp relational-database

我正在尝试获取ID列表(la find('list')),但无法弄清楚如何使用相关的模型条件。

我的协会是: Product hasAndBelongsToMany Category Product belongsTo Manufacturer

我想查找类别ID列表中的产品ID列表,并且具有某个制造商seo_url。我已经尝试了大量包含条件,引用其他模型的条件,甚至尝试使用find('all')来查看我的条件是否可行,但无法获得任何结果。

我设法使用Product-> query()获得了一个,但它不是列表格式。我可以遍历数组并获取ID或其他任何内容,但感觉非常糟糕。我想确保Cake仍然对我的查询进行所有安全检查,以及其他任何自动化操作。这是我工作的查询:

$all_results = $return['Category']['all_results'] = $this->Product->query('
    SELECT `Product`.`id`
        FROM `categories_products` as `CategoriesProduct`
        JOIN `products` as `Product` ON (`CategoriesProduct`.`product_id` = `Product`.`id`)
        JOIN `manufacturers` as `Manufacturer` ON (`Product`.`manufacturer_id` = `Manufacturer`.`id` AND `Manufacturer`.`seo_url` = \''.$manufacturer.'\')
        WHERE `CategoriesProduct`.`category_id` IN ('.implode(',', $search_categories).')
');

返回

[all_results] => Array
    (
         [0] => Array
            (
                [Product] => Array
                    (
                        [id] => 101787
                    )

            )

        [1] => Array
            (
                [Product] => Array
                    (
                        [id] => 100781
                    )

            )

        [2] => Array
            (
                [Product] => Array
                    (
                        [id] => 101887
                    )

            )

        [3] => Array
            (
                [Product] => Array
                    (
                        [id] => 101888
                    )

            )

    )

注意:$search_categories是类别ID的列表(即:array(12,42,24,5)

3 个答案:

答案 0 :(得分:3)

对于相关模型,CakePHP对于conditions可能有些奇怪。特别是与HABTM的关系。即使recursive设置为最高值(即2)。有关HABTM的详细信息,请查看文档。

尝试以下方法。虽然从上面来看,我认为它不会起作用:

$conditions = array('Category.id' => $category_ids, 'Manufacturer.seo_url' => $manufacturer);
$this->Product('list', array('recursive' => 1, 'conditions' => $conditions));

另外,尽可能避免使用query()。 MVC的重点是将数据显示逻辑隔离开来。使用像query()之类的东西就可以打破它。

答案 1 :(得分:3)

你想要的结果的问题是,如果你在相关模型上使用条件,那么Cake不会给你一个剥离的结果数组。

这是因为Cake只会在您的相关模型上使用这些条件,并在相关模型的条件为真的情况下返回结果。

如果您想要获得仅具有特定类别的产品,则需要通过类别模型进行查询,因为这样您就可以使用产品上的条件。这看起来像这样:

$this->Category->find('all', array('conditions' => array('Category.id' => 2));

这将只返回所需类别及其相关产品。 但是,如果你想要一个列表,这不是很令人满意,因为你必须手动进行转换。

我希望看一下Linkable Plugin,它应该能够准确地为您提供所需的功能,因为它像您在查询中一样使用连接扩展了Cake。这样就可以在相关模型上获得具有条件的结果。

答案 2 :(得分:0)

做一个正常的条件,然后变成列表格式。

$this->loadModel('AlertStatuses');  
$lists = $this->AlertStatuses->find('all', [ 
'conditions'=>['AlertStatuses.id > 2']]);
$alert_statuses  = array();
foreach($lists as $list) {
  $alert_statuses[$list->id] = $list->name;
}
$this->set('alert_statuses', $alert_statuses);
相关问题