【问题标题】:Foreign Key in Laravel 5.1 - NO RelationshipLaravel 5.1 中的外键 - 没有关系
【发布时间】:2017-09-20 18:35:06
【问题描述】:

需要帮助的人!我的迁移出了什么问题,它没有在users 表和posts 表之间建立关系。这是我所做的:

  1. 迁移用户表
  2. 创建帖子表
  3. 使用外键迁移帖子表

用户迁移

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password', 60);
            $table->rememberToken();
            $table->timestamps();
        });
    }

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



帖子迁移

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title', 255);
            $table->text('content');
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

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



我的数据库没有任何问题。看看我的数据库:



比较与此:



.. 我正在使用 Laravel 5.1

【问题讨论】:

  • 有什么错误吗?发布到?
  • 检查它们的列定义(类型、大小)在数据库上是否相等。
  • @MayankPandeyz 没有错误显示。
  • @TahaPaksu 是的,它们是一样的。
  • 迁移文件夹中的帖子和用户迁移的顺序是什么?

标签: mysql laravel database-migration


【解决方案1】:

您需要分两步添加它。 Schema::create() 仅用于创建表。

要添加关系,您需要将其写入Schema::table()

尝试以下:

CreatePostsTable

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        $table->string('title', 255);
        $table->text('content');
        $table->timestamps();
    });

    Schema::table('posts', function($table) {
        $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    });
}

【讨论】:

  • @LaravelMan 如果表已经创建,您需要添加新的迁移文件并在该文件中分配外键代码,然后运行迁移。
  • @MeeraTank 我也试过了,还是不行
  • 如果您没有任何数据。回滚迁移并再次运行。
  • @PankitGami 我没有任何数据,嗯,我试过你的答案,但还是不行。
猜你喜欢
  • 2019-07-20
  • 2015-12-05
  • 1970-01-01
  • 2021-10-29
  • 1970-01-01
  • 2015-11-13
  • 2016-02-27
  • 2015-08-01
  • 2016-01-02
相关资源
最近更新 更多