【发布时间】:2017-09-28 08:27:39
【问题描述】:
我目前正在做一个学校项目,我的数据库遇到了这个问题, 我想与视频和类别建立关系,这是我的两个表。 视频表:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateVideosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('videos', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->default('');
$table->string('url')->default('');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('img_url')->default('');
$table->integer('views')->nullable();
$table->integer('rating')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('videos');
}
}
还有分类表:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
当我在控制台中运行 php artisan migrate:refresh 我得到这个错误:
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General error: 1215
Cannot add foreign key constraint (SQL: alter table `videos` add constraint
`videos_category_id_foreign` foreign key (`category_id`) references
`categories` (`id`))
[PDO异常] SQLSTATE[HY000]: 一般错误:1215 无法添加外键约束
我不明白为什么,因为当我改变这个时:
$table->foreign('category_id')->references('id')->on('categories');
到这里:
$table->foreign('category_id')->references('id')->on('users');
它有效,然后我没有任何错误,我希望有人能帮助我解决这个问题!
【问题讨论】:
标签: php mysql sql database laravel