2012-12-26 115 views
0

相關模型的檢索,我檢索數據隨機順序:CakePHP的模型關聯 - 對HABTM

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

我已經設置了產品模型HABTM關係。正如您所看到的,我正在獲取'我們愛'列表中的所有產品。現在,我希望我檢索的那些產品是隨機的。但它們不是,而是像SQL中所看到的那樣,MySQL在ProductList模型上隨機化。這是爲什麼?我如何才能在產品上進行隨機獲取?

得到的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`) 

回答

0

編輯:

有這麼多不同的方式來處理這一點;從用戶的產品列表中獲取隨機產品。你可以用PHP做 - 只需找到所有的產品,然後用rand()從返回的數組中選擇。您可以設置模型查詢條件。該名單繼續...

我可能會創建一個名爲RandomProduct ProductList的產品模型的別名。

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

然後,您可以使用中可容納的行爲,這樣,當你需要它這個模型僅檢索:當您設置的關係,你可以設置檢索到的產品查詢。 (如果recursive找到的值大於-1,則不需要執行此操作,但我通常將其作爲最佳實踐來執行此操作,以便我的模型僅查詢他們需要的數據。)以下代碼將返回任何名爲「我們愛'和與該列表關聯的「隨機」產品。

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

好的,但是複製我以前的病狀的語法是什麼?你的'...'是重要的一點,但是被省略了。 – alieninlondon