【发布时间】:2017-04-09 13:21:06
【问题描述】:
我正在尝试使用 for 循环将所有这些数据保存到数据库中,并且 addr_types 已经大于 1。但我在数据库中只有一行。 它应该插入多个 addr_types 但它只插入一行。
use App\Models\MyModels;
use DB;
class ClientCbcAddress extends MyModels
{
protected $table = 'address';
//protected $fillable = ['role_id','name', 'email','username'];
protected $hidden = ['created_at', 'updated_at'];
public $timestamps = false;
private $Add_rules = [
'country_id' => 'required',
'province_Id' => 'required',
'id_number_1' => 'required',
'address_en' => 'required',
];
public function SaveClientAddress($data, $id)
{
if (!$this->Check_validator($data, $this->Add_rules)){
return $this->Check_validator($data, $this->Add_rules);
}
for ($i = 0; $i <= count($data['addr_types']) - 1; $i++) {
$city_code = '';
$postal_code = '';
if (trim($data['provinces']) === 'PNH' && trim($data['country']) === 'KHM') {
$city_code = 'PNH';
$postal_code = $data['provinces'][$i];
}
$identification = new self();
$identification->client_id = (int)$id;
$identification->country_id = (int)$data['country'][$i];
$identification->province_Id = (int)$data['provinces'][$i];
$identification->district_id = (int)$data['district'][$i];
$identification->commune_id = (int)$data['commune'][$i];
$identification->village_id = (int)$data['villages'][$i];
$identification->address_type = $data['addr_types'][$i];
$identification->address_en = $data['address_en'][$i];
$identification->address_kh = $data['address_kh'][$i];
$identification->city_code = $city_code;
$identification->postal_code = $postal_code;
if($identification->save()){
return $identification->attributes['id'];
}
}
}
}
数据库
【问题讨论】:
-
但是你得到什么样的错误?
-
没有错误但只插入了一行
-
你有任何唯一键吗?
-
无论如何你为什么将
SaveClientAddress函数放入模型而不是控制器中? -
我认为你在第一次从循环中保存后正在做
return $identification->attributes['id'];,所以你在数据库中只得到一条记录。