1
我完全新的Yii框架和關係型數據庫,但我需要創建一個小的應用程序來控制合作伙伴和活動。合作伙伴(socios)可以有許多活動和活動可以有許多合作伙伴所以,這裏是我的數據庫Yii的簡單的關係問題
CREATE TABLE `actividades` (
`id` int(11) NOT NULL,
`nombre` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `axs` (
`id_socio` int(11) NOT NULL,
`id_acti` int(11) NOT NULL,
KEY `id_socio` (`id_socio`),
KEY `id_acti` (`id_acti`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `socios` (
`id` int(11) NOT NULL,
`nombre` varchar(45) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ADD CONSTRAINT `id_socio` FOREIGN KEY (`id_socio`) REFERENCES `socios` (`id`) ON DELETE
CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT `id_acti` FOREIGN KEY (`id_acti`) REFERENCES `actividades` (`id`) ON DELETE
CASCADE ON UPDATE CASCADE;
這是我的模型的關係
**Socios**
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'actividadesrel' => array(self::HAS_MANY, 'Actividades', 'id_socio'),
);
}
**Activades**
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'sociosrel' => array(self::HAS_MANY, 'Socios', 'id_socio'),
);
}
這是我的社會的控制器
public function actionCreate()
{
$model=new Socios;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Socios']))
{
$model->attributes=$_POST['Socios'];
if($model->save()) {
foreach ($_POST['Socios']['actividadesrel'] as $actividadId) {
$socioActividad = new Axs;
$socioActividad->socio_id = $model->id;
$socioActividad->acti_Id = $actividadId;
if (!$socioActividad->save()) print_r($socioActividad->errors);
}
}
}
$this->render('create',array(
'model'=>$model,
));
}
最後在我的社會創建表格
<div class="row">
<?php echo $form->labelEx($model,'Actividades del socio'); ?>
<?php echo $form->dropDownList($model, 'actividadesrel', CHtml::listData(
Actividades::model()->findAll(), 'id', 'nombre'), array('multiple'=>'multiple',
'size'=>5)
); ?>
<?php echo $form->error($model,'actividadesrel'); ?>
</div>
現在,每次我嘗試創建一個新的合作伙伴(社會)我得到這個消息:
Please fix the following input errors:
ID cannot be blank.
這是推動我完全瘋了:P。我假設我的錯誤是關於Yii和ActiveRecord以及與關係數據庫相關的其他垃圾的理解很差。
你能幫我嗎?
謝謝!
我想知道在這MANY_MANY關係,如果我們插入一個新的「ACTIVIDADES」,那麼如何還插入一個進入連接表,在這種情況下,「AXS」。 – 2011-10-30 03:35:19
有一些方便的擴展,使這更容易(http://www.yiiframework.com/search/?q=many_many&type=extension)。基本上,在你的afterSave()方法中,你只需要做一些數據庫插入。你可以直接用SQL來做這件事,或者爲你的關係表創建一個AR模型,並保存它(如下所示:http://www.yiiframework.com/forum/index.php?/topic/8170-best-method - 用於節能一對多,多對多的記錄) – thaddeusmt 2011-10-30 17:12:48