字段没有默认值||外键

时间:2017-01-30 16:19:12

标签: laravel foreign-keys

我正在尝试在projectController中使用外键,以获取它所属域的名称。但是,当我尝试运行此命令时:php artisan db:seed --class = ProjectTableSeeder。我收到了这个错误: '域ID'没有默认值。

请问任何想法,它来自哪里?

这是我的迁移create_project_table:

public function up()
{
    Schema::create('projects', function (Blueprint $table) {
        $table->increments('id', true);
        $table->string('title');
        $table->string('code');         
        $table->integer('domain_id')->nullable();
        $table->foreign('domain_id')->references('id')->on('domains');

        $table->timestamps();
    });
}

Project_Controller:

public function create()
{
    //

    $arrondissements = Arrondissement::pluck('arrondissement', 'id');
    return view('pros.create', compact('arrondissements'));
}

1 个答案:

答案 0 :(得分:0)

错误消息'domain_id' doesn't have a default value表示您已运行

 $ php artisan migrate

在实际将nullable()约束添加到外键之前。请注意,对于大多数数据库,nullable列的默认值为NULL

为了解决这个问题,我建议你重新创建表,意思是,用所有表删除整个数据库,然后再次重新运行migrate。这只是在您可以承受丢失数据的情况下。

如果没有,您可以创建另一个迁移,通过添加nullable约束来更改表。此外,您可能还需要更新数据。