CakePHP模型关联 - 检索HABTM关联模型的随机顺序

时间:2012-12-26 20:19:02

标签: mysql cakephp model-associations

我正在检索数据:

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

我已经与产品型号建立了HABTM关系。正如您所看到的,我正在获取“我们喜欢的”列表中的所有产品。现在,我希望我检索的那些产品是随机的。但它们不是,而是在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`)

1 个答案:

答案 0 :(得分:0)

修改

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

我可能会在ProductList中为Product Model创建一个名为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'
        )
    );