gpt4 book ai didi

php - 在 Controller 中执行存储功能时如何获取模型的 ID?

转载 作者:搜寻专家 更新时间:2023-10-31 21:19:25 24 4
gpt4 key购买 nike

我想插入两个通过多对多关系关联的表,但我需要将用户 ID 传递给相关表,我该如何获取它?

这是 storegetCountry 函数:

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]: Integrity constraint violation:

1048 Column 'user_id' cannot be null (SQL: insert into user_country (country_id, user_id) values (1, ?))

最佳答案

错误告诉您,如果没有先创建用户(这是您的外键被投入使用),它不能将国家附加到用户。

您需要做的就是先保存用户,以便 Laravel 在尝试将该用户附加到国家/地区时知道用户 ID。

$dbUser->save();

foreach (explode(',', str_replace(' ', '', $user['PAIS-USUARIO'])) as $c) {
$country = $this->getCountry($c);
$dbUser->countries()->save($country);
}

关于php - 在 Controller 中执行存储功能时如何获取模型的 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57824554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com