php - Yii2 无法插入带有 id(PK) 的属性(FK)

标签 php mysql yii2

我有 id 有来自模型/订单的 PK(Auto Inc) 与来自模型/预购的 FK id_order 的关系,在我的 CRUD 操作中,例如 actionCreate,我无法将 attibutes 预购插入表,因为 id(PK) 来自订单总是空的。我该如何解决这个问题?

这是我的 Controller

$cartPositions = Yii::$app->cart->getPositions();

  if (!$cartPositions or $cartPositions === null) {
      return $this->redirect(['index']);
  }

  $dataProvider = new ArrayDataProvider([
      'allModels' => $cartPositions,
  ]);

    $model = new Order();
    $model_po = new Preorder();
    $postData = Yii::$app->request->post();

        if ($model->load($postData) && $model_po->load($postData)) {
        //model->save(false);
        $model->status = 5;
        $model_po->id_order = $model->id;
        $model->total_cost = Yii::$app->cart->getCost();
        $model->date = date('Y-m-d H:i');
        $model->data = Yii::$app->cart->getSerialized();
        $model_po->name = $model->name;
        $model_po->phone = $model->phone;
        $model_po->remarks = $model->message;
        $model_po->created_at = $model->date;
        //$model_po->save();
        if (Model::validateMultiple([$model, $model_po]) && $model->save(false) && $model_po->save()) {
            Yii::$app->session->setFlash('success', 'Thank You');
            Yii::$app->mailer->compose('order/html', [
                'model' => $model,
                //'model_po' => $model_po,
                'dataProvider' => $dataProvider,
            ])
                //->setFrom(Yii::$app->params['email']['from'])
                // ->setTo(Yii::$app->params['email']['to'])
                // ->setSubject('The site posted a new order')
                // ->send();

                ->setFrom(Yii::$app->params['email']['from'])
                ->setTo(Yii::$app->params['email']['to'])
                ->setSubject('The site posted a new Preorder')
                ->send();

            Yii::$app->cart->removeAll();
            return $this->render('orderSuccess', [
                'model' => $model,
                //'model_po' => $model_po,
            ]);
        }
    } else
    {return $this->render('create_po', [
      'model' => $model,
      'model_po' => $model_po,
      'dataProvider' => $dataProvider,
    ]);}
  }

型号/订单

public function rules()
{
    return [
        [['status', 'total_cost', 'date', 'data', 'name', 'phone'], 'required'],
        [['code_order'], 'autonumber', 'format'=>'orderNum', 'digit'=>4],
        [['status', 'total_cost'], 'integer'],
        [['date'], 'safe'],
        [['data', 'message'], 'string'],
        [['name', 'email', 'phone'], 'string', 'max' => 255]
    ];
}

模型/预购

public function rules()
{
    return [
        [['id_order', 'address'], 'required'],
        [['id_order'], 'integer'],
        [['created_at', 'updated_at'], 'safe'],
        [['address', 'remarks'], 'string', 'max' => 500],
        [['id_order'], 'exist', 'skipOnError' => true, 'targetClass' => Order::className(), 'targetAttribute' => ['id_order' => 'id']],
    ];
}

错误信息:

Integrity constraint violation – yii\db\IntegrityException SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'id_order' cannot be null The SQL being executed was: INSERT INTO preorder (address, id_order, name, phone, remarks, created_at) VALUES ('', NULL, 'Name', '121324325', '', '2016-07-23 17:01')

错误信息:数组 ( [0] => 23000 [1] => 1048 [2] => 列 'id_order' 不能为空

我尝试了 getPrimaryKey() 并且最后插入 id() 不起作用,我尝试删除 $modelpo->id_order = $model->id 结果是两个表已填充但 id_order 为 0

最佳答案

$model->id 在 $model->save() 成功之前为空,因此您不应在此之前将其值分配给 $model_po->id_order。

这是transaction的好地方因此您可以先验证数据,然后确保订单已保存,然后使用正确的 id_order 保存预购。

看看link()方法也是如此。

关于php - Yii2 无法插入带有 id(PK) 的属性(FK),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38544446/

相关文章:

java - 如何终止长时间运行的报告

mysql - 使 API (Wordpress) 日期可与 Coldfusion 一起使用

Mysql 通过连接从一张表中获取另一张表的结果

javascript - 保留 jquery ui 选项卡的状态

php - Ajax .click 从列表中仅选取第一行值

php - 在 mysql 表上使用空间索引选择最近的地理坐标不起作用

php - 创建一个 zip 文件

php - 获取用户配置文件 - dektrium/yii2-user Yii2

html - 导航栏 yii2 中的容器流体

php - 如何在yii2中制作下拉列表?