【问题标题】:CakePHP model associations - Random order on retrieve of associated model for HABTMCakePHP 模型关联 - 为 HABTM 检索关联模型时的随机顺序
【发布时间】:2012-12-26 20:19:01
【问题描述】:

我正在检索数据:

$mydata = $this->ProductList->find('all', array('order' => 'rand()', 'conditions' => array('name' => 'we love')));

我已与 Product 模型建立了 HABTM 关系。如您所见,我正在获取“我们喜欢”列表中的所有产品。现在,我希望我检索的那些产品是随机的。但它们不是,相反,MySQL 在 ProductList 模型上是随机的,正如您在 SQL 中看到的那样。这是为什么?我怎样才能获得产品的随机提取?

生成的 MySQL 查询:

SELECT `ProductList`.`id`, `ProductList`.`name` FROM `database`.`product_lists` AS `ProductList` WHERE `name` = 'we love' ORDER BY rand() ASC

SELECT `Product`.`id`, `Product`.`category_id`, `Product`.`name`, `Product`.`price`, `Product`.`description`, `ProductListsProduct`.`product_list_id`, `ProductListsProduct`.`product_id` FROM `database`.`products` AS `Product` JOIN `database`.`product_lists_products` AS `ProductListsProduct` ON (`ProductListsProduct`.`product_list_id` = 3 AND `ProductListsProduct`.`product_id` = `Product`.`id`)

【问题讨论】:

    标签: mysql cakephp model-associations


    【解决方案1】:

    编辑:

    有很多不同的方法可以解决这个问题;从用户的产品列表中获取随机产品。您可以使用 PHP 来完成 - 只需找到所有产品,然后使用 rand() 从返回的数组中进行选择。您可以设置模型查询条件。名单还在继续……

    我可能会为 ProductList 中的 Product 模型创建一个别名,称为 RandomProduct。您可以在设置关系时为检索到的产品设置查询:

    public $hasMany = array(
        'RandomProduct' => array(
            'className'     => 'Product',
            'foreignKey'    => 'product_list_id',
            'order'         => 'Rand()',
            'limit'         => '1',
            'dependent'     => true
        )
    );
    

    然后,您可以使用可包含行为,以便仅在需要时检索此模型。 (如果 recursive 的查找结果大于 -1,则无需执行此操作,但我通常将其作为最佳实践,以便我的模型仅查询他们需要的数据。)以下将返回任何名为 ' 的 ProductList我们喜欢'以及与该列表相关的“随机”产品。

    $mydata = $this->ProductList->find(
        'all', 
        array(
            'conditions' => array(
                'name' => 'we love'
                )
            ),
            'contain' => array(
                'RandomProduct'
            )
        );
    

    【讨论】:

    • 好的,但是复制我之前的条件的语法是什么?您的“...”是重要的部分,但被省略了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-05
    相关资源
    最近更新 更多