我有一個Artist
模型和Product
模型。他們的協會如下:CakePHP - 使用find()方法
Artist hasMany Product
Product belongsTo Artist
的Artist
可能沒有任何Products
。如何使用find()
方法列出所有藝術家以及他們擁有的Products
的編號?
我有一個Artist
模型和Product
模型。他們的協會如下:CakePHP - 使用find()方法
Artist hasMany Product
Product belongsTo Artist
的Artist
可能沒有任何Products
。如何使用find()
方法列出所有藝術家以及他們擁有的Products
的編號?
只要您的關係設置正確,這就是您所需要做的。
$results = $ArtistModel->find('all');
從藝術家控制器,你可以這樣做:
$this->Artist->find('all')
要訪問它在一個視圖中,您將需要使用()設置是這樣的:
$this->set('artists', $this->Artist->find('all'));
然後,您可以看到通過在視圖中執行print_r($artists);
來完成數據。
您可以使用counterCache函數在緩存上存儲每個Artist的產品數量。
或者,如果你願意,你可以(手動)使用ORM,它應該是這樣的:
$this->Artist->find('all',array('fields'=>array('Artist.*','COUNT(Product.id) as count_products')
'joins'=>array(array('table' => 'products',
'alias' => 'Product',
'type' => 'INNER',
'conditions' => array('Artist.id = Product.artist_id'))),
'group'=>'Artist.id'
));
希望這有助於
您可以使用一個簡單的find
調用是這樣的:
$artists = $this->Artist->find('all');
返回和陣列是這樣的:
array(
[0] => array(
[Artist] => array(
'id' => 1,
'other_field' => 'other_value',
...
),
[Product] => array(
[0] => array(
'id' => 1,
...
),
[1] => array(
'id' => 2,
...
)
)
)
[1] => array(
[Artist] => array(
'id' => 2,
'other_field' => 'other_value',
...
),
[Product] => array(...)
)
)
然後,您可以遍歷結果,並得到你需要的信息:產品
foreach ($artists as $artist) {
echo $artist['Artist']['name'];
echo count($artist['Product']);
}
你的意思是「COUNT()」? – pleasedontbelong
@pleasedontbelong - 是的 – freshest