2016-08-01 108 views
2

我有一个产品模型可以将信息保存到数据库中的产品表格中,但我也有价格表格,颜色表格和尺寸表格在我的数据库中和表格上所有的产品信息,包括通过产品控制器和产品型号的价格,尺寸和颜色,现在我想知道如何在表格中以不同方式节省价格,尺寸和颜色。下面是一个快照如何在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']保存到有相应的列

+0

从您的问题的标题'如何使用...'的答案是使用'使用':) – SaidbakR

回答

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, 
     ]); 
    } 
} 

,为View:

<?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这样的参数。

+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(); 
} 
+0

好的谢谢你们的想法我知道我可以这样做,但我想也许这是可能的没有模型分开的颜色,大小也许我可以只改变表名称动态,但我认为从所有的答案我得到它几乎是不可能的,所以我需要为每个表创建一个模型 – sam

相关问题