php 如何创建2个外国到同一个表laravel 10?

utugiqy6  于 2023-10-15  发布在  PHP
关注(0)|答案(1)|浏览(126)

我在Laravel中创建了一个迁移,我需要引用同一个表2次。我解释说:“inventory”表有“responsible”和“created by”字段,它们引用了user表。在某些情况下,负责人和创作者可能是同一人。
这是迁移代码:

  1. Schema::create('inventory', function (Blueprint $table) {
  2. $table->id();
  3. $table->integer('type');
  4. $table->string('state', 50);
  5. $table->timestamps();
  6. $table->foreignId('user_id')->constrained(
  7. table: 'user',
  8. indexName: 'created_inventory_id'
  9. )->cascadeOnUpdate()->restrictOnDelete();
  10. $table->foreignId('user_id')->constrained(
  11. table: 'user',
  12. indexName: 'responsible_inventory_id'
  13. )->cascadeOnUpdate()->restrictOnDelete();
  14. $table->foreignId('area_id')->constrained(
  15. table: 'area',
  16. indexName: 'area_inventory_id'
  17. )->cascadeOnUpdate()->restrictOnDelete();
  18. });

当我运行迁移时,它给了我以下错误:

  1. SQLSTATE[42701]: Duplicate column: 7 ERROR: column "user_id" was specified more than once (Connection: pgsql, SQL: create table "inventory"

我该怎么解决呢?

mctunoxg

mctunoxg1#

要为“inventory”表中的“inventory manager”和“inventory creator”字段引用同一个“user”表,您应该为它们指定不同的列名。以下是解决此问题的更新迁移代码:

  1. Schema::create('inventory', function (Blueprint $table) {
  2. $table->id();
  3. $table->integer('type');
  4. $table->string('state', 50);
  5. $table->timestamps();
  6. $table->foreignId('inventory_creator_user_id')->constrained(
  7. table: 'user',
  8. indexName: 'created_inventory_id'
  9. )->cascadeOnUpdate()->restrictOnDelete();
  10. $table->foreignId('inventory_manager_user_id')->constrained(
  11. table: 'user',
  12. indexName: 'responsible_inventory_id'
  13. )->cascadeOnUpdate()->restrictOnDelete();
  14. $table->foreignId('area_id')->constrained(
  15. table: 'area',
  16. indexName: 'area_inventory_id'
  17. )->cascadeOnUpdate()->restrictOnDelete();
  18. });
展开查看全部

相关问题