0
我使用CakePHP 2.3.x版本自定義內使用中可容納查找
我有以下的hasMany關係的模型:
class Product extends AppModel {
public $name = 'Product';
public $actsAs = array('Containable');
public $findMethods = array('instockinactive' => true);
public $hasMany = array(
'Listing' => array(
'className' => 'Listing',
'foreignKey' => 'product_id',
'dependent' => false,
'order' => 'Listing.market ASC'
)
數據庫看起來像下面這樣。我想選擇'Listing.listingstatus'='Inactive'的所有'產品'。我想我應該可以用Contain做到這一點。
array(
(int) 0 => array(
'Product' => array(
'id' => '15',
'skutype' => 'Standard',
'sku' => 'dba:43253R',
'mpn' => '43253R',
'brand' => 'Hamilton Beach',
'upc' => '040094916559',
'isbn' => '',
'ean' => '',
'gtin' => '',
'jan' => '',
'stock' => 'Yes',
'condition' => 'New',
'created' => '1406243817',
'modified' => '1406243817'
),
'Listing' => array(
(int) 0 => array(
'id' => '32',
'product_id' => '15',
'market_id' => '1',
'sku' => 'dba:43253R',
'market' => 'jskdistributing',
'listingstatus' => 'Active',
'itemid' => '191260995302',
'created' => '2014-07-24 19:24:50',
'modified' => '2014-07-24 19:24:50'
)
)
),
(int) 1 => array(
'Product' => array(
'id' => '229',
'skutype' => 'Standard',
'sku' => 'dba:48465',
'mpn' => '48465',
'brand' => 'Hamilton Beach',
'upc' => '040094484652',
'isbn' => '',
'ean' => '',
'gtin' => '',
'jan' => '',
'stock' => 'Yes',
'condition' => 'New',
'created' => '1407615778',
'modified' => '1407615778'
),
'Listing' => array(
(int) 0 => array(
'id' => '238',
'product_id' => '229',
'market_id' => '1',
'sku' => 'dba:48465',
'market' => 'jskdistributing',
'listingstatus' => 'Inactive',
'itemid' => '191280736083',
'created' => '2014-08-09 16:33:55',
'modified' => '2014-08-09 16:33:55'
)
)
)
定製發現如下:
protected function _findInstockinactive ($state, $query, $results = array()) {
if ($state === 'before') {
$query['order'] = array('Product.sku' => 'asc');
$query['conditions'] = array('Product.stock' => 'Yes');
$query['contain'] = array('Listing' => array(
'conditions' => array('Listing.listingstatus =' => 'Inactive')
);
return $query;
}
return $results;
}
這一發現的結果是,它會選擇每個產品記錄,並和每一個清單記錄。清單沒有顯示如下所示的內容。
array(
(int) 0 => array(
'Product' => array(
'id' => '15',
'skutype' => 'Standard',
'sku' => 'dba:43253R',
'mpn' => '43253R',
'brand' => 'Hamilton Beach',
'upc' => '040094916559',
'isbn' => '',
'ean' => '',
'gtin' => '',
'jan' => '',
'stock' => 'Yes',
'condition' => 'New',
'created' => '1406243817',
'modified' => '1406243817'
),
'Listing' => array()
)
),
(int) 1 => array(
'Product' => array(
'id' => '229',
'skutype' => 'Standard',
'sku' => 'dba:48465',
'mpn' => '48465',
'brand' => 'Hamilton Beach',
'upc' => '040094484652',
'isbn' => '',
'ean' => '',
'gtin' => '',
'jan' => '',
'stock' => 'Yes',
'condition' => 'New',
'created' => '1407615778',
'modified' => '1407615778'
),
'Listing' => array()
)
)
謝謝,saveario,對於我的迴應很抱歉,很抱歉。這非常有幫助,我很欣賞你回答問題的時間。 – 2014-09-10 15:40:31