[Yii2笔记]027从多模型中获取数据(Getting Data for Multiple Models) [ 技术分享 ]
说明
学习Yii Framework 2(易2框架)的过程是漫长的,也是充满乐趣的,以下是我学习Yii2框架时对官网英文资料(请参见原文网址)的翻译和代码实现,提供了较完整的代码,供你参考。不妥之处,请多多指正!
原文网址:
http://www.yiiframework.com/doc-2.0/guide-input-multiple-models.html
本文主题:从多模型中获取数据(Getting Data for Multiple Models)
当处理一些复杂数据时,可能需要使用多个不同的模型去收集客户的输入。例如,假定用户登录信息存储在user表中,用户配置信息存储在profile表中,你想要通过User模型和Profile模型去收集一个客户的信息。在Yii的模型和表单支持下,你可以解决这个问题,与处理单模型并没有太多的不同。 接下来,我们将介绍如何创建一个从User和Profile模型中收集数据的表单。
首先,编写收集user和profile数据的控制器动作的代码如下:
namespace app\controllers;
use Yii;
use yii\base\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use app\models\User;
use app\models\Profile;
class UserController extends Controller{
public function actionUpdate($id){
$user = User::findOne($id);
if (!$user) {
throw new NotFoundHttpException("The user was not found.");
}
$profile = Profile::findOne($user->profile_id);
if (!$profile) {
throw new NotFoundHttpException("The user has no profile.");
}
$user->scenario = 'update';
$profile->scenario = 'update';
if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {
$isValid = $user->validate();
$isValid = $profile->validate() && $isValid;
if ($isValid) {
$user->save(false);
$profile->save(false);
return $this->redirect(['user/view', 'id' => $id]);
}
}
return $this->render('update', [
'user' => $user,
'profile' => $profile,
]);
}
}
在update动作中,我们首先从数据库中加载需要更新的$user 和$profile 模型,然后调用yii\base\Model::load()使用用户输入来填充这两个模型。如果成功,我们将验证这两个模型并存储它们,否则将渲染如下内容的update视图:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin([
'id' => 'user-update-form',
'options' => ['class' => 'form-horizontal'],
]) ?>
<?= $form->field($user, 'username') ?>
...other input fields...
<?= $form->field($profile, 'website') ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
正如你所看到的,在update视图中将使用$user 和$profile 两个视图来渲染输入项。
(全文完)
共 0 条回复
没有找到数据。
阿江
注册时间:2015-10-18
最后登录:2024-03-03
在线时长:186小时21分
最后登录:2024-03-03
在线时长:186小时21分
- 粉丝94
- 金钱16816
- 威望160
- 积分20276