laravel – 为包含主键和外键的迁移文件运行“php artisan migrate”时出现语法错误或访问冲突错误

嗨,我想在我的数据库中创建2个名为“品牌”的表格. “产品”.我为“品牌”创建了名为“create_brand”的迁移文件,其中包含:

public function up()
{
    Schema::create('brand', function($table){
        $table->increments('brand_id');
        $table->string('brand_name', 100);
    });
}

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

名为“create_product”的“product”的迁移文件包含:

public function up()
{
    Schema::create('product', function($table){
        $table->increments('skuid');
        $table->integer('brand_id')->unasigned();
    });

    Schema::create('product', function($table){
        $table->foreign('brand_id')->references('brand_id')->on('brand')->onDelete('cascade');
    });


}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::table('product', function($table){
        $table->dropForeign('brand_id');
    });

    Schema::drop('product');
}

现在,当我运行“php artisan migrate”时,我收到错误:

  [Illuminate\Database\QueryException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error i
  your SQL syntax; check the manual that corresponds to your MySQL server v
  ersion for the right syntax to use near ') default character set utf8 colla
  te utf8_unicode_ci' at line 1 (SQL: create table `product` () default chara
  cter set utf8 collate utf8_unicode_ci)


  [PDOException]
  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error i
  n your SQL syntax; check the manual that corresponds to your MySQL server v
  ersion for the right syntax to use near ') default character set utf8 colla
  te utf8_unicode_ci' at line 1

如果有人能帮我解决这个问题,我将非常感激:)谢谢.

最佳答案
使用Schema :: create一次.要编辑表,请使用Schema :: table

当使用外键时,类型应该是unsignedInteger.如果您创建一个基本整数并尝试在其上放置一个外键,它将失败.

将您的密码更改为

public function up()
{
    Schema::create('product', function($table){
       $table->increments('skuid');
       $table->unsignedInteger('brand_id');
    });

    Schema::table('product', function($table){
       $table->foreign('brand_id')->references('brand_id')->on('brand');
    });
}

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

转载注明原文:laravel – 为包含主键和外键的迁移文件运行“php artisan migrate”时出现语法错误或访问冲突错误 - 代码日志