Laravel多对一表迁移

时间:2017-08-31 16:19:07

标签: php laravel eloquent

我有这个迁移代码

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

class CreateAvatarsTable extends Migration
{

    public function up()
    {
        Schema::create('avatars', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name', 100)->nullable();
            $table->string('filename', 255)->nullable();
            $table->text('detail')->nullable();
            $table->text('pos_x')->nullable();
            $table->text('pos_y')->nullable();

            $table->integer('avatars_id')->nullable();
              $table->foreign('avatars_id')->references('id')->on('avatars')->onUpdate('cascade')->onDelete('cascade');

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


    public function down()
    {
        Schema::dropIfExists('avatars');
    }
}

当我运行生成迁移的代码时

php artisan migrate:refresh

我得到了这个结果:

  

[Illuminate \ Database \ QueryException] SQLSTATE [42000]:语法错误   或访问冲突:1103表名不正确'' (SQL:alter table   avatars添加con straint avatars_avatars_id_foreign外键   (avatars_id)在删除级联上引用``(id

     

[Doctrine \ DBAL \ Driver \ PDOException] SQLSTATE [42000]:语法错误   或访问冲突:1103表名不正确''

     

[PDOException] SQLSTATE [42000]:语法错误或访问冲突:   1103表名称不正确''

4 个答案:

答案 0 :(得分:1)

要在同一张表中分配外键,应使用此键,  直到Laravel 5.8

SyntaxError in line 11 of /media/jim/Elements/Happy/test/Snakefile:
invalid syntax

答案 1 :(得分:0)

字段ID使用无符号整数数据类型

$table->unsignedInteger('avatars_id')->nullable();

答案 2 :(得分:0)

更改以下行

$table->integer('avatars_id')->nullable();

$table->integer('avatars_id')->unsigned();

因为外键id应该是无符号整数

答案 3 :(得分:0)

您正尝试在尚不存在的表格上设置引用;尝试如下:

public function up() {
  Schema::create('avatars', function(Blueprint $table) {
    $table - > increments('id');
    $table - > string('name', 100) - > nullable();
    $table - > string('filename', 255) - > nullable();
    $table - > text('detail') - > nullable();
    $table - > text('pos_x') - > nullable();
    $table - > text('pos_y') - > nullable();
    $table - > integer('avatars_id') - > nullable();
    $table - > softDeletes();
    $table - > timestamps();
  })

  Schema::table('avatars', function($table) {
    $table - > foreign('avatars_id') - > references('id') - > on('avatars') - > onUpdate('cascade') - > onDelete('cascade');
  });

}