PHP Laravel,方法updateOrCreate的替换



以下问题是更大项目的一部分。作为一名大三学生,我的任务是替换Laravel的方法updaterOrCreate,该方法用于创建令牌。使用的方法是:

public function creaOUp(
string $token,
string $carId,
int $exDate,
string $log,
int $driverId
): DriverToken {
$token = DriverToken::onWriteConnection()->updateOrCreate([
'car_id' => $carId,
'driver_id' => $driverId
], [
'token' => $token,
'ex_date' => $exDate,
'login' => $log,
]);
return $token;
}

方法在这样的项目中被调用:

private $driverTokenRepository;
//....
return $this->driverTokenRepository->creaOUp(
(string)$jwt,
$deviceData->uid,
$jwt->getClaim('exp'),
$claims->getLogin(),
$claims->getDriverParentId()
//....

我已经取代方法updateOrCreate:的方法

public function creaOUp(
string $token,
string $carId,
int $exDate,
string $log,
int $driverId
): DriverToken {
$token = DriverToken::query()
->where([
'car_id' => $carId,
'driver_id' => $driverId,
])
->first();

if ($token !== null) {
$token->update([
'token' => $token,
'car_id' => $carId,
'ex_date' => $exDate,
'login' => $log, 

]);
} else {
$token = DriverToken::create([
'token' => $token,
'car_id' => $carId,
'ex_date' => $exDate,
'login' => $log,
'driver_id' => $driverId,
]);
}
return $token;
}

我确信它会起作用,但我有错误:

"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'token' cannot be null (SQL: insert into `driver_tokens` (`token`, `car_id`, `ex_date`, `login`, `driver_id`) values (?, cba567D1, 2425452525, HUGO_315, 3))"

我做错了什么?为什么令牌为空?最初Laravel的updateOrCreate成功了,也许我真的不理解这个方法?

已解决:

首先,感谢sandy的帮助,这是我在StackOverflow上的第一篇文章:D

问题出在param$token上。它被用作字面上的令牌,也被用作查询。我刚刚将查询中的$token更改为:

public function creaOUp(
string $token,
string $carId,
int $exDate,
string $log,
int $driverId
): DriverToken {
$quer = DriverToken::query()
->where([
'car_id' => $carId,
'driver_id' => $driverId,
])
->first();

if ($quer !== null) {
$quer->update([
'token' => $token,
'car_id' => $carId,
'ex_date' => $exDate,
'login' => $log, 

]);
} else {
$quer = DriverToken::create([
'token' => $token,
'car_id' => $carId,
'ex_date' => $exDate,
'login' => $log,
'driver_id' => $driverId,
]);
}
return $quer;
}

它解决了问题。:(

最新更新