gpt4 book ai didi

php - 如何使用自定义自增主键 Laravel 添加模型

转载 作者:行者123 更新时间:2023-11-29 12:16:52 24 4
gpt4 key购买 nike

我正在创建一个播种机,它将(部分)数据从我们的生产数据库读取到我们的暂存环境中。

所以我得到了一个名为“类别”的模型,它的主键设置如下:

                                                             Table "public.categories"
Column | Type | Modifiers |
-----------------+--------------------------------+---------------------------------------------------------+
id | integer | not null default nextval('categories_id_seq'::regclass) |

因为我从我的产品数据库中选择了几个类别,所以它的 ID 不是连续的(它们看起来像这样:)

 id
-----
3
9
7
1
11
13
15
19
21
23
25
43
45
49
51
53
55
57
61

现在我还有一个自定义种子文件,我想在其中创建虚假类别。当然,我必须确保我正在创建一个 ID 大于具有最高 ID 的类别的类别。我是这样做的:

$factory->define(App\Category::class, function (Faker\Generator $faker) {
// to avoid duplicating ids
$lastCategory = Category::select('id')->orderBy('id','desc')->first();

$category = new Category();
$category->id = $lastCategory->id+1;
$category->ref = str_random(20);
$category->image = $faker->imageUrl(300, 300);
$category->priority = rand(0, 100);
$category->save();

但我一直收到这个错误:

[Illuminate\Database\QueryException] SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "categories_pkey" DETAIL: Key (id)=(13) already exists. (SQL: insert into "categories" ("ref_translation", "ref", "parent_id", "top_parent_id", "image", "priority", "updated_at", "created_at") values (translatable.category.ref.HDHCDuNPC4vZoHBB, sandwiches, 124, 124, https://cdn.filepicker.io/api/file/TqB5OvCdSxGDFecrSyrU, 0, 2018-02-20 08:38:20, 2018-02-20 08:38:20) returni ng "id")

[Doctrine\DBAL\Driver\PDOException] SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "categories_pkey" DETAIL: Key (id)=(13) already exists.

尽管与原始 postgresql 语句执行相同的操作工作得很好:

insert into categories (id, ref_translation,ref,image,priority) values (200, 'translatable.category.ref.ZAxcHj4hOziemQyz', 'LP2a1bY81IGSza0eHVSqdfsdfdsffds', 'image_name', 1);
INSERT 0 1

我如何通过 Laravel 的 Eloquent ORM 让它工作?

更新

作为引用,这是我的类生成器的样子:

$factory->define(App\Category::class, function (Faker\Generator $faker) {
$category = App\Category::create([
'ref' => str_random(20),
'image' => $faker->imageUrl(300, 300),
'priority' => rand(0, 100),
]);
$top_parent_id = $category->id;

return [
'ref' => str_random(21),
'parent_id' => $top_parent_id,
'top_parent_id' => $top_parent_id,
'image' => $faker->imageUrl(300, 300),
'priority' => rand(0, 100),
];
});

最佳答案

这使它起作用

$lastCategory = \App\Category::orderBy('id','desc')->first();
\DB::statement('alter sequence categories_id_seq restart with '.(intval($lastCategory->id)+1));

引用资料

关于php - 如何使用自定义自增主键 Laravel 添加模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48881049/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com