Yii2多模型循环保存报错
Yii2 multiple models loop save error
我有一个 table,我必须在其中保存多个数据,在我的控制器中我已经实现了这个操作:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
$model = new SlidersImages();
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
if ($model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()) {
$s['image_'.$key] = $model;
$model->display_order = $value;
//$result = ($t = $model->update()) ? $result + $t : $result;
$result = $model->save() && $result;
}
}
}
return $result;
}
接收到的数据是正确的,但结果不是], 为什么模型没有正确保存?
谢谢
重要的是你打电话的时候
$model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
您不会更改 $model
对象本身。本质上你是在打电话:
SlidersImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
因此,稍后当您调用 $model->save()
时,您将保存一个具有空属性的 $model
对象(您只更改了 display_order
)
我的建议是:尝试将 ->all()
调用的结果分配给新的 var,然后使用它:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
$models = SliderImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all();
if (count($models)) {
// loop through $models and update them
}
}
}
return $result;
我有一个 table,我必须在其中保存多个数据,在我的控制器中我已经实现了这个操作:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
$model = new SlidersImages();
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
if ($model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()) {
$s['image_'.$key] = $model;
$model->display_order = $value;
//$result = ($t = $model->update()) ? $result + $t : $result;
$result = $model->save() && $result;
}
}
}
return $result;
}
接收到的数据是正确的,但结果不是], 为什么模型没有正确保存?
谢谢
重要的是你打电话的时候
$model::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
您不会更改 $model
对象本身。本质上你是在打电话:
SlidersImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all()
因此,稍后当您调用 $model->save()
时,您将保存一个具有空属性的 $model
对象(您只更改了 display_order
)
我的建议是:尝试将 ->all()
调用的结果分配给新的 var,然后使用它:
public function actionUpdateOrder($id){
/*DA TESTARE*/
//$result = 0;
$result = true;
$s = new Session;
if ($new_order = Yii::$app->request->post('order')) {
//$s['us_model'] = 0;
foreach ($new_order as $key => $value) {
$models = SliderImages::find()->where(['slider_id' => $id, 'image_id' => $key])->all();
if (count($models)) {
// loop through $models and update them
}
}
}
return $result;