简体   繁体   English

Laravel mysql错误关系数据库?

[英]Laravel mysql error relational databases?

Syntax error or access violation: 1072 Key column 'collection_id' doesn't exist in table (SQL: alter table products add constraint products_collection_id_foreign foreign key ( collection_id ) references collections ( id ) on delete cascade)语法错误或访问冲突:1072 表中不存在键列“collection_id”(SQL:alter table products添加约束products_collection_id_foreign外键( collection_id )在删除级联时引用collectionsid ))

So im having this issue trying to relation products with collections with a collection_id.所以我遇到了这个问题,试图将产品与具有 collection_id 的集合联系起来。

This is my collection migration这是我的收藏迁移

    class CreateCollectionsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('collections', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name');
            $table->string('author');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('collections');
    }
}

This is my product migration这是我的产品迁移

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
            $table->string('name');
            $table->integer('price');
            $table->string('src');
            $table->unsignedBigInteger('collection_id');
            $table->foreign('collection_id')->references('id')->on('collections')->onDelete("cascade");
            $table->integer('amount');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

您的迁移是否正确运行您还可以检查创建表时的迁移顺序,如果集合是在产品之前创建的,如果产品是在集合之前创建的,它会抛出此错误,因为集合尚未创建,还有一个快捷方式定义外键是

$table->foreignId('collection_id')->constrained()->cascadeOnDelete();

You can do it the following way.您可以通过以下方式进行。

$table->unsignedBigInteger('collection_id');
$table->foreign('collection_id')->references('id')->on('collections')->onDelete("cascade");

And one more thing run the following command :还有一件事运行以下命令:

php artisan migrate:fresh 

or或者

 php artisan migrate:refresh 

hope your problem will be resolved.or can follow the following URL Laravel migration: "Foreign key constraint is incorrectly formed" (errno 150)希望您的问题能够得到解决。或者可以按照以下 URL Laravel 迁移:“外键约束格式错误”(errno 150)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM