首页 > 解决方案 > 在 Laravel 上保存后如何获取正确的 Id 参数

问题描述

我有一个当前在 C# 站点上工作的 SQL 服务器数据库,因此我从头开始创建了一个 Laravel 项目来使用该数据库。一切正常,我可以在上面查阅和写入数据,但我遇到的问题是当我在表中创建一个新对象时,我在新的 Class 函数之后没有得到正确的 id 参数。

这是我的控制器:

$softwareRequest = new SoftwareRequest;
    $softwareRequest->OwnerManager = $request->input('contactApplicationManager');
    $softwareRequest->TestorName = $request->input('contactTesterRequestedBy');
    $softwareRequest->TestorPhone = $request->input('contactTesterPhone');
    $softwareRequest->TestorEmail = $request->input('contactTesterEmail');

    $softwareRequest->save();

如果我 DD() 变量$softwareRequest我得到:

#attributes: array:5 [▼
"OwnerEmail" => "test@test.com"
"TestorName" => "Testor Name"
"TestorPhone" => "3456787455"
"TestorEmail" => "test1@test.com"
"Id" => 57980

数据库上的 Id 设置为Id(大写的 I)而不是 id 但是我保存后得到的 Id 参数不是正确的(甚至没有关闭),一旦我去数据库手动检查,它确实存储了具有正确 ID 号的数据,因为我使用的是 eloquent 并且我为每个表创建了模型,如何在 ->save() 之后立即为新保存的数据获取正确的 Id 参数?我需要在保存后立即获取 ID,因为我需要用它来在另一张桌子上存储其他东西。

这就是模型所具有的:

protected $table = 'SoftwareRequest';
protected $primaryKey = 'Id';
public $timestamps = false;

我把主键作为 Id 因为这是它在数据库中设置的方式,如果我拿走这条线

protected $primaryKey = 'Id';

我得到相同的但id小写

#attributes: array:5 [▼
"OwnerEmail" => "test@test.com"
"TestorName" => "Testor Name"
"TestorPhone" => "3456787455"
"TestorEmail" => "test1@test.com"
"id" => 57981

但同样,这甚至没有接近它应该得到的正确 ID,下一个数字的增量是 5917,我认为问题可能更多在于表格在模型上是硬编码的,知道吗?

标签: phplaravellaravel-7.x

解决方案


尝试这个:

$softwareRequest =SoftwareRequest::create([

  'OwnerManager' = $request->input('contactApplicationManager'),
 'TestorName' = $request->input('contactTesterRequestedBy'),
 'TestorPhone' = $request->input('contactTesterPhone'),
'TestorEmail' = $request->input('contactTesterEmail'),
]);

然后:

dd($softwareRequest);

推荐阅读