如何在yii2中的一个模型中使用多个表

时间:2016-08-01 01:08:10

标签: php mysql yii2

我有一个产品型号,可以将信息保存到数据库中的产品表中,但我的数据库和表格中也有价格表,颜色表和尺寸表,我将获得所有产品信息,包括价格,尺寸和颜色产品控制器和产品型号,现在我想知道如何在表格中以不同的方式保存表格上的价格,尺寸和颜色。下面是快照

public function actionCreate(){
$data = \Yii::$app->request->post();
$model = new Product();
$model->title = $data['title'];
$model->name = $data['name'];
}

现在如何将此表格名称更改为价格,尺寸或颜色,以便将$data['size'] and $data['color'] and $data['price']保存到各自的列

2 个答案:

答案 0 :(得分:2)

一个模型与一个数据库表相关联。

至于处理不同类型的多个模型,官方文档中有一篇好文章 - Getting Data for Multiple Models

省略细节,这里是控制器的代码片段:

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部分,尤其是验证规则 Massive Assignment 段落。您应该避免处理$_POST这样的参数。

答案 1 :(得分:0)

每张桌子都应该有一个模型。在价格,颜色和尺寸表中插入产品的ID。在所有其他表中添加product_id。试试这个:

    public function actionCreate()
{
    $data = \Yii::$app->request->post();
    $model = new Product();
    $model->title = $data['title'];
    $model->name = $data['name'];
    $model->save();
    $getlast=Yii::$app->db->getLastInsertId();

    $model = new Price();
    $model->price=Yii::$app->request->post('price');
    $model->product_id = $getlast;
    $model->save();

    $model = new Size();
    $model->size=Yii::$app->request->post('size');
    $model->product_id = $getlast;
    $model->save();
}