我正在尝试获取 ID 列表(find('list')
),但无法弄清楚如何在相关模型条件下做到这一点。
我的协会是: Product hasAndBelongsToMany Category
Product belongsTo Manufacturer
我想查找类别 ID 列表中具有特定制造商seo_url的产品 ID 列表。我已经尝试了大量包含条件,引用其他模型的条件,甚至尝试使用 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)
)
你想要的结果的问题在于,如果你在相关模型上使用条件,Cake 不会给你一个剥离的结果数组。
发生这种情况是因为 Cake 只会在您的相关模型上使用这些条件,并在您的相关模型上以 true 的条件返回给您结果。
如果您想取回仅具有特定类别的产品,则需要通过类别模型进行查询,因为这使您可以使用产品上的条件。这可能看起来像这样:
$this->Category->find('all', array('conditions' => array('Category.id' => 2));
这将仅返回您想要的类别及其相关产品。但是,如果您想要一个列表,这不是很令人满意,因为您必须手动进行转换。
我宁愿看一下可链接插件,它应该为您提供您想要的功能,因为它像在查询中一样使用连接扩展了 Cake。这样就可以在相关模型上获得有条件的结果。
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()
这样的东西只会打破它。
执行正常条件,然后更改为列表格式。
$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);