我想按标签推荐相关产品,并按最匹配的排序顺序。
Product 和 Tag 之间的 HABTM 模型关联
class Product extends AppModel {
//..
var $hasAndBelongsToMany = array("Tag");
//..
}
在标签模型中反之亦然。连接表名称也是“products_tags”。
对于示例..
//just sample of Product contain Tag data
$products[0]['Tag'] = array('touch', 'phone', '3G', 'apple'); //iPhone
$products[1]['Tag'] = array('phone', '3G', 'BB'); //BB
$products[2]['Tag'] = array('touch', '3G', 'apple'); //iPad
$products[3]['Tag'] = array('3G', 'air card'); //3G air card
在此示例中,与 iPhone 最相关的按优先级排序的是..
- ipad(在 3 个标签中找到)
- BB(在 2 个标签中找到)
- 航空卡(仅匹配 1 个)
Cake 如何使用 Model find() 来获取子查询,如下所示:
SELECT DISTINCT (product_id) AS id, (
/* sub-query counting same tags*/
SELECT COUNT(*) FROM tags as Tag
LEFT JOIN products_tags AS ProductTag ON ( Tag.id = ProductTag.tag_id )
WHERE product_id = id
AND Tag.name IN ( 'touch', 'phone', '3G', 'apple' )
) AS priority /*this is weight count by how many same tags*/
FROM `tags` as Tag
LEFT JOIN products_tags AS ProductTag ON ( Tag.id = ProductTag.tag_id )
WHERE Tag.name
IN ( 'touch', 'phone', '3G', 'apple' )
ORDER BY priority DESC
上面的 SQL 查询完全返回了我需要的内容。但我找不到将参数解析为 CakePHP 的 AppModel->find() 方法的方法。