我有一个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