我有来自模型/订单关系的PK(Auto Inc)与来自models / preorder的FK id_order,在我的CRUD操作中,例如actionCreate,我无法在表中插入attibutes preorder,因为id(PK)从订单总是null。我该如何解决这个问题?。
这是我的控制器
$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']],
];
}
错误信息:
完整性约束违规 - yii \ db \ IntegrityException SQLSTATE [23000]:完整性约束违规:1048列' id_order'不能为空 正在执行的SQL是:INSERT INTO
preorder
(address
,id_order
,name
,phone
,remarks
,created_at
)价值观('',NULL,'姓名',' 121324325','',' 2016-07-23 17 :01&#39)
错误信息:数组 ( [0] => 23000 [1] => 1048 [2] =>专栏' id_order'不能为空
我尝试了getPrimaryKey()和最后一次插入id()不起作用,我试图删除$ modelpo-> id_order = $ model-> id结果是两个表填充但id_order为0
答案 0 :(得分:1)
$ model-> id在成功$ model-> save()之前为空,因此您不应在此之前将其值分配给$ model_po-> id_order。
这是transaction的好地方,因此您可以先验证数据,然后确保订单已保存,然后使用正确的id_order保存预订。
同时查看link()方法。
答案 1 :(得分:0)
为什么不使用afterSave()?它将定义解决您的问题