我需要在yii模型动作创建或Addipblock()中运行forloop,并保存每条记录,尽管forloop结束,然后将其重定向到查看管理员,
我的第一条记录从1开始到50结束,所以在数据库中应该添加50条记录。
我的代码是这样的:
`public function actionAddipblock(){
$model=new IpManager('addipblock');
if(isset($_POST['IpManager'])){
$model->attributes=$_POST['IpManager'];
$starting_ip = $_POST['IpManager']['starting_ip'];
$ending_ip = $_POST['IpManager']['ending_ip'];
if($model->validate('addipblock')){
for($ip = $starting_ip; $ip <= $ending_ip; $ip++){
$model->ip = $ip;
$model->server = $_POST['IpManager']['server'];
$model->client = $_POST['IpManager']['client'];
$model->status = $_POST['IpManager']['status'];
$model->creation_date = date("Y-m-d H:i:s");
}
if($model->save()){
$this->redirect(array('admin'));
}
else{
echo 'Error:';
}
}
}
$this->render('addipblock',array('model'=>$model));
}`
但是当我运行这段代码时,只保存一条记录,直到forloop结束才保存所有记录。 伙计你会建议我这个吗?我该怎么办呢?
答案 0 :(得分:3)
在你的forloop中尝试这个,
for($ip = $starting_ip; $ip <= $ending_ip; $ip++){
// you need to null your model primary key
$model->id = null; // like this
$model->ip = $ip;
$model->server = $_POST['IpManager']['server'];
$model->client = $_POST['IpManager']['client'];
$model->status = $_POST['IpManager']['status'];
$model->creation_date = date("Y-m-d H:i:s");
$model->isNewRecord = true;
$model->save();
}