我有一个产品模型,将信息保存到数据库中的产品表中,但我的数据库中也有价格表、颜色表和尺寸表,在表单上我将通过以下方式获取所有产品信息,包括价格、尺寸和颜色产品 Controller 和产品型号,现在我想知道如何在各自的表格中以不同的方式保存表格上的价格、尺寸和颜色。下面是快照
public function actionCreate(){
$data = \Yii::$app->request->post();
$model = new Product();
$model->title = $data['title'];
$model->name = $data['name'];
}
现在我如何将此表名称更改为价格或尺寸或颜色才能保存$data['size']和$data['color']和$data['price']
到相应的列
最佳答案
一个模型与一个数据库表关联。
关于处理不同类型的多个模型,官方文档中有一篇很好的文章 - Getting Data for Multiple Models .
省略细节,这里是 Controller 的代码片段:
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,
]);
}
}
查看:
<?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() ?>
这篇文章也可能有用 - Collecting tabular input 。它涵盖从相同类型的多个模型收集数据。
另请阅读Models部分,特别是验证规则和大规模分配段落。您应该避免像这样处理 $_POST
参数。
关于php - yii2如何在一个模型中使用多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38689754/