如何在Cakephp 中查找连接表?
How to find in joining tables Cakephp?
嗯,这就是问题所在。我有一个 table 'Store' 加入了 table 'Product',所以每个商店(例如沃尔玛)都有一系列产品:(咖啡、牛奶、番茄酱等)我需要做一个查找,只检索 2 个随机 Stores,其中条件是那些 商店 必须至少有一种产品。
我正在这样查找:
$this->Store->find('all', array( 'conditions' => ...... , 'order' => 'rand()','limit' => 2));
但是此查找可以检索到 Store 没有任何产品。
我无法在 table Product 中进行查找,因为多个产品具有相同的商店,并且随机可能导致两次出现相同的商店。
像您提到的那样在 Products table 中查找,然后过滤以仅获取 DISTINCT store_id的。这将过滤掉两次获得同一家商店。类似于:
$this->Store->Product->find('all', array(
'order' => 'rand()',
'limit' => 2,
'fields' => array('DISTINCT(Store.id)')
));
或者只是分组依据 Store.id
:
$this->Store->Product->find('all', array(
'order' => 'rand()',
'limit' => 2,
'group' => 'Store.id'
));
嗯,这就是问题所在。我有一个 table 'Store' 加入了 table 'Product',所以每个商店(例如沃尔玛)都有一系列产品:(咖啡、牛奶、番茄酱等)我需要做一个查找,只检索 2 个随机 Stores,其中条件是那些 商店 必须至少有一种产品。
我正在这样查找:
$this->Store->find('all', array( 'conditions' => ...... , 'order' => 'rand()','limit' => 2));
但是此查找可以检索到 Store 没有任何产品。
我无法在 table Product 中进行查找,因为多个产品具有相同的商店,并且随机可能导致两次出现相同的商店。
像您提到的那样在 Products table 中查找,然后过滤以仅获取 DISTINCT store_id的。这将过滤掉两次获得同一家商店。类似于:
$this->Store->Product->find('all', array(
'order' => 'rand()',
'limit' => 2,
'fields' => array('DISTINCT(Store.id)')
));
或者只是分组依据 Store.id
:
$this->Store->Product->find('all', array(
'order' => 'rand()',
'limit' => 2,
'group' => 'Store.id'
));