Laravel数据库添加外键不成功原因

2017-06-16 17:24:18

在此之前需要建一个product_property表,代码如下:

Schema::create('product_property', function(Blueprint $table)
{
$table->increments('id');
$table->string('name',200)->unique();
$table->timestamps();
$table->engine = 'InnoDB';
});

建完后给products表添加字段product_property_id为product_property表id的外键,代码如下:

Schema::table('products', function(Blueprint $table)
{
$table->integer('product_property_id')->default(3);
$table->foreign('product_property_id')->references('id')->on('product_property');

结果,运行php artisan migrate提示添加外键失败,查看已添加成功的product_property查看id的属性为integer unsigned,故把添加外键的代码改为:

Schema::table('products', function(Blueprint $table)
{
$table->unsignedInteger('product_property_id')->default(3);
$table->foreign('product_property_id')->references('id')->on('product_property');
}); 

总结,Laravel用migrate给数据库表添加外键,外键的属性一定要跟主键表的字段完全一致,否则添加不成功。另外$table->increments('id');添加的id字段属性为unsignedInteger