我对Yii Framework和Relational数据库完全陌生,但我需要创建一个小应用程序来控制合作伙伴和活动。合作伙伴(socios)可以有很多活动,活动可以有很多合作伙伴所以,这是我的数据库
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'),
);
}
这是我的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>
现在,每当我尝试创建一个新的合作伙伴(socio)时,我都会收到以下消息:
Please fix the following input errors:
ID cannot be blank.
这让我完全疯狂:P。我认为我的错误是对Yii和ActiveRecord以及与关系数据库相关的其他狗屎的理解很差。
你能帮助我吗?
感谢!!!!
答案 0 :(得分:3)
我认为这里有一些事情发生。
1)此错误(ID cannot be blank.
)来自您的Socio模型。做两件事来解决这个问题:
id
主键设置为auto_increment。2)您正在建立两个“HAS_MANY”关系。我会设置一个“MANY_MANY”关系,如下所示:
Socio模型:
public function relations()
{
return array(
'actividades'=>array(self::MANY_MANY, 'Actividades',
'axs(id_socio, id_acti)'),
);
}
Actividades模型:
public function relations()
{
return array(
'socios'=>array(self::MANY_MANY, 'Socios',
'axs(id_acti, id_socio)'),
);
}
您可以在Ultimate Guide中了解有关关系的更多信息。
我希望这有助于您走上正确的轨道!