CakePHP子查询HABTM中的SQL关系

时间:2010-08-04 06:51:11

标签: mysql cakephp subquery has-and-belongs-to-many cakephp-appmodel

我想通过最匹配的标签和排序顺序来推荐相关产品。

产品与标签之间的HABTM模型关联

class Product extends AppModel {
//..
var $hasAndBelongsToMany = array("Tag");
//..
}
Tag模型中的

反之亦然。 join-table name也是“products_tags”。

for Ex.sample ..

//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按优先级排序最相关的是..

  1. ipad(找到3个标签)
  2. BB(找到2个标签)
  3. aircard(仅匹配1个)
  4. 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()方法的方法。

1 个答案:

答案 0 :(得分:0)

如果此sql的结果不使用分页(假设普通网页中的相关产品是3-5个条目),为什么不使用这个复杂的SQL呢?

即。在您的产品模型中创建一个与函数相关的产品()

然后使用$ this-> query($ sql)

示例代码将是:

class Product extends AppModel {
  //..
  var $hasAndBelongsToMany = array("Tag");
  //..
  function relatedProducts($parameters){
    $sql = "select..... where ....$parameters...";
    return $this->query($sql);
  }
}

然后你可以通过

在控制器中使用它
$this->Product->relatedProducts($some_parameters);
相关问题