问题

我正在尝试插入通过多对多关系相关的两个表,但我需要用户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]:完整性约束违反:

1048列’user_id’不能为null(SQL:插入user_country(country_id,user_id)值(1,?))

  最佳答案

错误告诉您,如果没有首次创建用户,它就不能将一个国家附加到用户身上(这是您的外键被放在工作中)。

您需要做的只是先保存用户,以便Laravel在尝试将该用户附加到该国时知道用户ID.

 $dbUser->save();

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

  相同标签的其他问题

phplaravellaravel-5