2016-09-28 55 views
1

我正在使用Laravel 5.3和MySQL。Laravel将外键引用移动到具有两列的主键?

如何添加Laravel外键对两列主键的引用?

下面是我的迁移脚本(在database/migrations/目录下)

有两列

public function up() 
{ 
    Schema::create('X', function (Blueprint $table) { 
     $table->integer('a')->unsigned(); 
     $table->integer('b')->unsigned(); 
     $table->primary(['a', 'b']); 
     $table->timestamps(); 
    }); 
} 

,并在另一个主键,

public function up() 
{ 
    Schema::create('Y', function (Blueprint $table) { 
     $table->increments('k'); 
     $table->foreign('c')->references(['a', 'b'])->on('X')->onDelete('cascade'); 
     $table->timestamps(); 
    }); 
} 

然而,这不是”这样工作:我怎么能做到这一点?

回答

2

使用添加外键约束到你的数据库Schema::table()代替Schema::create()

下面,片段表示修正:

// File name: 2016_09_28_create_x_table.php 
public function up() 
{ 
    // Create table X 
    Schema::create('X', function (Blueprint $table) { 
     $table->integer('a')->unsigned(); 
     $table->integer('b')->unsigned(); 
     $table->primary(['a', 'b']); 
     $table->timestamps(); 
    }); 
} 


// File name: 2016_09_28_create_y_with_foreignkey_table.php 
public function up() 
{ 
    // Create table Y 
    Schema::create('Y', function (Blueprint $table) { 
     $table->increments('k'); 
     $table->integer('c')->unsigned(); 
     $table->timestamps(); 
    }); 

    // Add Foreign key 
    Schema::table('Y', function (Blueprint $table) { 
     $table->foreign('c')->references('a')->on('X')->onDelete('cascade'); 
    }); 
} 

记住unsigned()应在c来施加。

+0

为你写的我都做了,但我没有得到它的工作。你有没有尝试过这种方法?有任何想法吗?非常感谢! – ackuser

+0

你得到了什么错误? – nyedidikeke

+0

更新了我的答案。 – nyedidikeke

0

这是我发现模拟组合键和FK指向在Laravel 5.3中工作的组合键的唯一方法 - 我错过了Laravel中更紧凑的解决方案。

总之,这里是我的代码

// File name: 2016_09_28_create_x_table.php 
public function up() 
{ 
    // Create table X 
    Schema::create('X', function (Blueprint $table) { 
     $table->increments('j'); 
     $table->integer('a')->unsigned(); 
     $table->integer('b')->unsigned(); 
     $table->unique(['a', 'b']); 

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


// File name: 2016_09_28_create_y_with_foreignkey_table.php 
public function up() 
{ 
    // Create table Y 
    Schema::create('Y', function (Blueprint $table) { 
     $table->increments('k'); 
     $table->integer('c')->unsigned(); 
     $table->timestamps(); 
    }); 

    // Add Foreign key 
    Schema::table('Y', function (Blueprint $table) { 
     $table->foreign('c')->references('j')->on('X')->onDelete('cascade'); 
    }); 
} 
相关问题