在我的项目中,我想在单独的数据库表行中保存多个数据。
在我的Controller操作中,代码如下:
$deletedProducts = new \app\models\ProductlinesDeleted();
$app = \app\models\Productlines::find()
->where(['product_id' => $id])->all();
foreach ($app as $prod){
$deletedProducts->productline_id = $prod->productline_id;
$deletedProducts->area_id = $prod->area_id;
$deletedProducts->product_id = $id;
$deletedProducts->internal_code = $prod->internal_code;
$deletedProducts->save();
$prod->delete();
}
return $this->redirect(['index']);
$ app 可以返回多个产品。因此我希望将数据保存在数据库表中。
例如我有
所以有2个产品有不同的区域。当我执行动作时,它必须保存:
产品1,数据库表中的第2行是区域2。
我怎样才能实现这一目标?谢谢..
答案 0 :(得分:1)
试试这个:
$app = \app\models\Productlines::find()
->where(['product_id' => $id])->all();
foreach ($app as $prod){
$deletedProducts = new \app\models\ProductlinesDeleted();
$deletedProducts->productline_id = $prod->productline_id;
$deletedProducts->area_id = $prod->area_id;
$deletedProducts->product_id = $id;
$deletedProducts->internal_code = $prod->internal_code;
$deletedProducts->save();
$prod->delete();
}
return $this->redirect(['index']);
答案 1 :(得分:0)
您可以在活动记录模型文件中使用 beforeDelete 事件,例如
public function beforeDelete() {
$deletedProducts = new \app\models\ProductlinesDeleted();
$deletedProducts->productline_id = $this->productline_id;
$deletedProducts->area_id = $this->area_id;
$deletedProducts->product_id = $this->product_id;
$deletedProducts->internal_code = $this->internal_code;
$deletedProducts->save();
return parent::beforeDelete();
}
此方法将调用表行的每条记录。因此,要删除产品,您的代码就像
$products = \app\models\Productlines::find()->where(['product_id' => $id])->all();
foreach ($products as $prod){
$prod->delete(); //beforeDelete event method will get call while you call this delete method.
}
return $this->redirect(['index']);
注意:只有在使用上述删除方法删除记录时,才会调用beforeDelete事件方法。