I am trying to do following but problem is that I am not getting the count right.
I have two Models with corresponding database table
Product
-id
-name
Version
-id
-version
-productId
(where productId is Foreign Key to Product.id)
In Version Model i have
public function relations()
{
return array(
'product' => array(self::BELONGS_TO, 'Product', 'productId'),
);
}
In Product Model I have
public function relations()
{
return array(
'versions' => array(self::HAS_MANY, 'Version', 'id'),
);
}
This is what I have in my product controller
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Product');
$this->render('index',array('dataProvider'=>$dataProvider,));
}
Now I have trying to display this in my View
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_itemview',
));
?>
In _itemview i want to show how many versions this product has. I tried following but always gives the count of 1. What am I doing wrong?
<b>Versions:</b>
<?php echo CHtml::encode(count($data->versions)); ?>
<br />
SJFriedl
(Steve)
April 1, 2011, 10:46pm
2
Looks to me like the versions relation is wrong:
// in Products model
public function relations()
{
return array(
// 'versions' => array(self::HAS_MANY, 'Version', 'id'), // NO
'versions' => array(self::HAS_MANY, 'Version', 'productId'), // YES
);
}
Try this maybe?
Looks to me like the versions relation is wrong:
// in Products model
public function relations()
{
return array(
// 'versions' => array(self::HAS_MANY, 'Version', 'id'), // NO
'versions' => array(self::HAS_MANY, 'Version', 'productId'), // YES
);
}
Try this maybe?
Yes!!! That worked! Now I know how HAS_MANY works. Thanks. I actually want to little bit more than show count and now I can move forward.
liu1084
(Liu1084)
April 2, 2011, 3:47am
4
ralation between product and version is has_many and belongs_to,
so your tables have foreign key between them.
Product
-id
-name
-version_id //foreign --> Version_id if you use mysql, you can alter table product add constraint FK_product_version
foreign key (version_id
) references version (id
) on delete cascade on update restrict;
Version
-id
-version
-productId // the same to above
and if you want to get the count for versions of a product ,you can declear in your relations:
‘versionsCount’ => array(self::STAT, ‘Product’, ‘productId’),
and you can access in your product view:
$model->comments->commentsCount;
if in version view:
$model->commentsCount;