【问题标题】:Laravel Model::create() returns the wrong idLaravel Model::create() 返回错误的 id
【发布时间】:2021-04-28 20:10:37
【问题描述】:

由于某种未知原因,Model::create() 后返回的主键值不是数据库中的主键值。我尝试将“递增”设置为 false,因为我发现这对其他人有用,但对我没有任何作用。

Laravel 框架 8.34.0

型号

class Provider extends Model
{
    protected $table = 'DoctorFacility';
    public $primaryKey = 'DoctorFacilityId';
    //public $incrementing = false; // tried this it just made the primary key empty
}

控制器

use App\Models\Provider;

class ProviderController extends Controller
{
    public function create(Request $request)
    {
        new Provider;
        $result = Provider::create([
            'first_name' => 'Jane',
            'last_name' => 'Doe'
        ]);

        // returns 45004857 the first test, and 45004859 on the 
        // second test (so it is incrementing in some way?)
        // while the actual id of the last created record
        // is "62644" on the first test, and "62645" on
        // the second test. 
        Log::critical($result->DoctorFacilityId); 
    }
}

【问题讨论】:

标签: laravel-8


【解决方案1】:

编辑:更新为按说明添加后不使用获取。

正如 Laravel 官方文档 here 中所述:如果您使用 create 方法,则需要在模型类上指定可填充或保护属性。

更新您的模型以对可填充数组使用受保护的而不是公开的,并确保将要填充的值添加到可填充数组中。

根据我使用复合主键的经验,在执行create of 或save 后,该值并不总是直接可用的。我知道这不是组合,而是您的主键的自定义值。

数据库:

更改您的数据库表“DoctorFacility”以使用名为“id”的列作为主键。

型号:

class Provider extends Model
{
    protected $table = 'DoctorFacility';
    protected $fillable = ['first_name', 'last_name']
}

控制器

$result = Provider::create([
            'first_name' => 'Jane',
            'last_name' => 'Doe'
        ]);

Log::critical($result->id);

【讨论】:

  • $fillable 被保护,并且 $fillable 被设置。 DoctorFacilityId 设置为自动递增,并且按照原始问题中的代码 cmets 中的描述工作。看起来像这样... ``` protected $fillable = [ 'PVId', 'Type', 'Created', 'CreatedBy', 'LastModified', 'LastModifiedBy', ]; ```
  • 我尝试将语法更改为 $provider->save() 并得到相同的结果。日志::critical(@$provider->DoctorFacilityId); // = 45005619,数据库中的DoctorFacilityId返回为“63602”
  • 好的,在你的问题中它没有显示 $fillable 已设置,这就是我提到它的原因。我知道它是受保护的,但你仍然可以在你的模型中将它添加为受保护的,它会覆盖它的父类的值。可填充数组中的 PVId 是什么,这与 DoctorFacilityId 的值是否不同?为什么不为您的数据库表使用默认值“id”?
  • 你能检查模型是否使用了正确的主键值吗?您可以运行 (new Provider)->->getKeyName();为了这。如果不正确,请将公共 $primaryKey 更新为模型中受保护的 $primaryKey,然后重试。
  • 正如 Lars 所问,你能澄清一下PVId 是什么吗?此外,您显示的$fillable 不包括first_namelast_name,因此您的代码实际上根本不应该能够创建记录?最后,为了绝对清楚,当您说“数据库中的 DoctorFacilityId 返回为“63602””时,您能否准确说明您是如何获取 ID 的?
猜你喜欢
  • 2020-05-24
  • 1970-01-01
  • 2015-06-27
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-17
  • 2020-02-20
  • 1970-01-01
相关资源
最近更新 更多