【问题标题】:CakePHP sub query SQL in HABTM relation在 HABTM 关系中的 CakePHP 子查询 SQL
【发布时间】:2023-03-26 13:50:01
【问题描述】:

我想按标签推荐相关产品,并按最匹配的排序。

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 最相关的是..

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

【问题讨论】:

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


    【解决方案1】:

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

    即在您的 Product 模型中创建一个函数 relatedProducts()

    然后使用 $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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多