[英]How to handle a create form with one to many relation in Yii?
I work with Yii 1.1. 我使用Yii 1.1。 I wish to make a create form, which creates a module. 我希望创建一个创建表单,以创建一个模块。 A module belongs to one user . 一个模块属于一个用户 。 A user has many modules . 用户有许多模块 。
tbl_user
----------
id
firstName
lastName
email
password
role
and 和
tbl_user_module
----------
id
name
academicYear
....
userId [FOREIGN KEY]
The relations in models are set up as follow: 模型中的关系设置如下:
Module.php Module.php
public function relations()
{
return array(
'user' => array(self::BELONGS_TO, 'User', 'userId'),
);
}
User.php User.php
public function relations()
{
return array(
'module' => array(self::HAS_MANY, 'Module', 'userId'),
);
}
A user uses a from to create a module, which belongs to him (logged in user). 用户使用from来创建属于他的模块(已登录用户)。 In the controller, I need to assign the userId foreign key as the logged in user. 在控制器中,我需要将userId外键分配为登录用户。
public function actionCreate()
{
$module = new Module();
// collect user input data
if(isset($_POST['Module']))
{
$module->attributes=$_POST['Module'];
$module->userId = Yii::app()->user->id; //assigned userID as logged in user
if($module->validate())
{
if($module->save())
{
$this->redirect(array('home/index'));
}
}
}
//render
$this->render('create',array('model'=>$module));
}
The form is not saved and throws an error: 表单未保存,并引发错误:
Property "Module.$userId" is not defined.
Obviously, I am not doing it right. 显然,我做错了。 How do I properly save a one-to-many relations in a form? 如何正确地以表格形式保存一对多关系?
解决了,我在Module.php中打错了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.