【问题标题】:Why this relationship is wrong?为什么这种关系是错误的?
【发布时间】:2021-12-08 16:11:48
【问题描述】:

我正在尝试建立多对多关系,其中许多品牌有许多产品类型,也有许多型号。而且很多产品类型有很多品牌:

所以这是我雄辩的关系:

Ptype.php:

    class Ptype extends Model
{
    public function marca(){
        return $this->belongsTo(Brand::class, 'brand_id', 'id');
    }
}

品牌.php:

public function ptype(){
        return $this->hasMany(Ptype::class, 'ptype_id', 'id');
    }

迁移:

brands_table:

public function up()
{
    Schema::create('models', function (Blueprint $table) {
        $table->id();
        $table->string('modelName');
        $table->unsignedBigInteger('brand_id');
        $table->foreign('brand_id')->references('id')->on('brands');
        $table->timestamps();
    });
}

ptypes:

public function up()
{
    Schema::create('ptypes', function (Blueprint $table) {
        $table->id();
        $table->string('productType');
        $table->unsignedBigInteger('brand_id');
        $table->foreign('brand_id')->references('id')->on('brands');
        $table->integer('created_by')->nullable();
        $table->integer('updated_by')->nullable();
        $table->timestamps();
    });
}

我做错了什么?

这是确切的错误:

SQLSTATE[HY000]: 一般错误: 1005 Can't create table `axis`.`ptypes` (errno : 150 "外键约束格式不正确") (SQL: alter table `ptypes` 添加约束`ptypes_brand_id_foreign`外键(`brand_id`)引用`b rands` (`id`))

【问题讨论】:

  • "references `brands` (`id`)"...这是实际的错误信息吗?如果是这样,似乎你在某处有一个错误的空白字符

标签: laravel eloquent laravel-7


【解决方案1】:

首先,检查您的迁移文件顺序。在我看来,它们应该是这样的:

  1. 品牌迁移
  2. 模型迁移
  3. ptypes 迁移

另外,您可以使用 foreignId 代替 foreign、references 等。

$table->foreignId('brand_id')->constrained(‘brands’);

所以,你可以删除这些;

$table->unsignedBigInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands');

【讨论】:

  • 我忘了更改迁移顺序。 ptypes 表试图在brands 表之前迁移。谢谢
猜你喜欢
  • 1970-01-01
  • 2016-07-06
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-07
相关资源
最近更新 更多