【发布时间】:2020-10-22 09:43:26
【问题描述】:
以下问题是更大项目的一部分。作为一名大三学生,我的任务是替换 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 就可以了,也许我真的不明白这个方法?
【问题讨论】:
-
错误信息明确指出您不能在令牌字段中设置空值,甚至它会为您提供表名。所以您只需要检查为什么该令牌值会变为空或将该字段设置为数据库表中的可空字段。
-
是的,我知道。但我唯一改变的是用我自己的方法从 updateOrCreate 替换,它应该以相同的方式工作。问题是方法 creaOUp 有什么问题。
-
你可以试试 $this->token 你查询令牌的地方,然后你把它作为婴儿车传递吗?