我试图插入到通过多对多关系相关的两个表中,但我需要将用户 ID 传递给相关表,我该如何获取?这是store和getCountry功能:public function store(Request $request){ ini_set('max_execution_time', 300); $users = $request->all(); try { DB::beginTransaction(); foreach ($users as $user) { $dbUser = $this->getUser($user['USERNAME']); Log::error($dbUser); $dbUser->name = $user['NOMBRE']; $dbUser->user_name = $user['USERNAME']; $dbUser->email = $user['CORREO']; $dbUser->last_name = $user['APELLIDO']; $dbUser->password = $user['PASSWORD']; $this->isSet('TIPO-USUARIO', $user); $user_type_id = $this->getUserId($user['TIPO-USUARIO']); $dbUser->user_type_id = $user_type_id->id; foreach (explode(',', str_replace(' ', '', $user['PAIS-USUARIO'])) as $c) { $country = $this->getCountry($c); $dbUser->countries()->save($country); } $dbUser->save(); } DB::commit(); } catch (Exception $e) { DB::rollBack(); throw new HttpException(500, 'My error message'); }}private function getCountry($id){ $country_id = Country::where('id', $id)->first(); return $country_id;}我现在得到的错误是:SQLSTATE[23000]:完整性约束违规:1048 列“user_id”不能为空(SQL:插入user_country(country_id,user_id)值(1,?))
1 回答

元芳怎么了
TA贡献1798条经验 获得超7个赞
该错误告诉您,在没有首先创建用户的情况下,它无法将国家/地区附加到用户(这是您的外键起作用)。
您需要做的就是先保存用户,以便 Laravel 在尝试将该用户附加到国家/地区时知道用户 ID。
$dbUser->save();
foreach (explode(',', str_replace(' ', '', $user['PAIS-USUARIO'])) as $c) {
$country = $this->getCountry($c);
$dbUser->countries()->save($country);
}
- 1 回答
- 0 关注
- 120 浏览
添加回答
举报
0/150
提交
取消