Yii 多模型形式的 actionUpdate() ?
在 Yii multimodel 表单我们刚刚使用 actionCreate() 在单个视图中创建两个模型的表单。好的,到这里一切都很好。但是当我们在单个视图中更新两个模型时多模型 模型将如何在这里定义? 让我给你举一个例子。假设数据库就像这样
=== Project ===
id
task_id(FK)
description
=== Task ===
id
name
description
所以在项目控制器的actionCreate()中,代码将是这样的
public function actionCreate()
{
$model=new Projects;
$tasks=new Projects;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Projects'],$_POST['Tasks']))
{
$model->attributes = $_POST['Projects'];
$tasks->attributes = $_POST['Tasks'];
$valid = $model->validate();
$valid = $tasks->validate();
if($valid)
{
$model->save(false);
$tasks->save(false);
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
'tasks'=>$tasks,
));
}
现在这里两个模型都已准备好创建。那么在 actionView()
和 actionUpdate()
中做什么?如何声明这两个模型?任何帮助和建议都将非常有价值。
In Yii multimodel form we just used actionCreate() to create the form of two models in a single view.Ok everything is fine upto here.But when we will update the two models in a single view of multimodel how the models will be defined here?
Let me give you one example.Just think the database is just like this
=== Project ===
id
task_id(FK)
description
=== Task ===
id
name
description
So In actionCreate() of the project controller,the code will be something like this
public function actionCreate()
{
$model=new Projects;
$tasks=new Projects;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Projects'],$_POST['Tasks']))
{
$model->attributes = $_POST['Projects'];
$tasks->attributes = $_POST['Tasks'];
$valid = $model->validate();
$valid = $tasks->validate();
if($valid)
{
$model->save(false);
$tasks->save(false);
$this->redirect(array('view','id'=>$model->id));
}
}
$this->render('create',array(
'model'=>$model,
'tasks'=>$tasks,
));
}
Now here the both models are ready for create. So what to do in actionView()
and actionUpdate()
?How to declare the both models?Any help and suggestions will be highly appriciable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这真的不一样吗?加载视图/更新时,您只需要在 GET 中包含 ID,它会告诉您要加载哪些模型。如果使用 ActiveRecord,模型将是 Projects::model()->findByPk($myId)。更新时,您可以像创建一样分配属性,但要确保首先从数据库加载模型。
Is this really different? When loading view / update you'll just need to have ID's in GET which tells you which models to load. Models will then be Projects::model()->findByPk($myId) if using ActiveRecord. When updating you can assign attributes as you do with create, but make sure the model is loaded from the database first.
您没有为任务模型创建任何对象。
You didn't create any object for Task model.