【问题标题】:how to make one to many relationship in my comment table如何在我的评论表中建立一对多关系
【发布时间】:2020-08-15 19:07:18
【问题描述】:

我已将此代码放入我的文章迁移中:

Schema::create('articles', function (Blueprint $table) {
    $table->id();
    $table->unsignedBigInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->string('author');
    $table->longText('description');
    $table->string('title');
    $table->text('tags');
    $table->timestamps();
});

然后我在我的评论迁移文件中使用此代码:

Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->unsignedInteger('article_id');
    $table->foreign('article_id')->references('id')->on('articles')->onDelete('cascade');
    $table->string('user_id');
    $table->string('user_name'); 
    $table->longtext('teks');
    $table->timestamps();
});

当我尝试使用 php artisan 进行迁移时,我的终端给出的错误消息是:

("SQLSTATE[HY000]: 一般错误:1005 无法创建表 projek_akhir_laravel.comments (errno: 150 "外键约束格式不正确")")

【问题讨论】:

    标签: javascript php node.js laravel


    【解决方案1】:

    在迁移中,$this->id(); 生成一个 unsignedBigInteger 字段。

    因此,包含外键的字段需要具有相同的格式:

    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('article_id');
        ....
    }
    

    你可以为外国人使用这个助手:

    $table->foreignId('article_id'); // generate an unsigned big integer field
    

    【讨论】:

      猜你喜欢
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多