很抱歉,我的标题可能无法解释我想要实现的目标,我有一系列国家/地区,我希望将其保存到以下数据库中是我的代码
public function actionCountries(){
$countries = array("AF" => "Afghanistan",
"AX" => "Åland Islands",
"AL" => "Albania",
"DZ" => "Algeria",
"AS" => "American Samoa",
"AD" => "Andorra",
"AO" => "Angola",
"AI" => "Anguilla",
"AQ" => "Antarctica",
"AG" => "Antigua and Barbuda",
"AR" => "Argentina",
"AM" => "Armenia",
"AW" => "Aruba",
"AU" => "Australia",
"AT" => "Austria",
"AZ" => "Azerbaijan",
"BS" => "Bahamas",
"BH" => "Bahrain",
"BD" => "Bangladesh",
"BB" => "Barbados",
"YE" => "Yemen",
"ZM" => "Zambia",
"ZW" => "Zimbabwe");
$model = new Country();
foreach($countries as $code => $name){
$model->code = $code
$model->code = $name
if($model->save()){
echo $model->countryId;
}
}
}
我想通过一次单击将所有国家/地区保存到数据库中,但我得到的结果是空的,如果我为save()方法提供了一个false参数,我将数组的最后一个元素保存到了数据库如下
$model = new Country();
foreach($countries as $code => $name){
$model->code = $code
$model->code = $name
if($model->save(false)){
echo $model->countryId;
}
}
this code will save only the last element in the array while the first code did nothing
对此感谢的任何帮助
答案 0 :(得分:0)
这是因为
$model = new Country();
在循环之外,所以你一遍又一遍地保存相同的模型。在循环中移动它。
顺便说一下 - 效率不高。请查看batchInsert()方法,以获得更加内存友好的方法。