【发布时间】:2018-10-21 06:34:24
【问题描述】:
我有一个关于 laravel 迁移表的问题。我在两张桌子之间有一对一的关系。 OrderLine 和工单。我已经将这两个函数放在模型 Ticket 和 OrderLine 中:
public function orderline()
{
return $this->hasOne('App\OrderLine');
}
public function ticket()
{
return $this->hasOne('App\Ticket');
}
并在迁移文件中创建_tickets_table 架构:
public function up()
{
Schema::create('tickets', function (Blueprint $table) {
$table->increments('id');
$table->integer('order_line_id')->unsigned(); //foreign key
$table->string('number');
$table->float('price');
$table->timestamps();
$table->foreign('order_line_id')->references('id')->on('order_lines');//relationship one to one between orderline & ticket tables
});
}
并在迁移文件中创建_order_lines_table 架构:
public function up()
{
Schema::create('order_lines', function (Blueprint $table) {
$table->increments('id');
$table->integer('ticket_id')->unsigned();//foreign key
$table->integer('order_id')->unsigned(); //foreign key
$table->float('total_order_line');
$table->timestamps();
$table->foreign('ticket_id')->references('id')->on('tickets');//relationship one to one between orderline & ticket tables
$table->foreign('order_id')// relationship one to many between order & order line tables
->references('id')->on('orders')
->onDelete('cascade');
});
}
当我做 php artisan migrate 时,我仍然有这个错误:
bruno@bruno-HP-EliteBook-840-G4:~/projetconcert$ php artisan migrate 迁移表创建成功。
Illuminate\Database\QueryException : SQLSTATE[HY000]: 一般错误: 1005 无法创建表gestion_concert_spectacle.#sql-e08_30d (errno: 150 "外键约束格式不正确") (SQL: alter table @987654326 @添加约束order_lines_ticket_id_foreign外键(ticket_id)引用tickets(id))
有人知道如何解决吗?谢谢你。布鲁诺
【问题讨论】:
-
为什么你在你的票和你的订单行id中使用foreign...你只需要使用一个foreign..你正在使用关系,所以无论何时你在ticket或order line中使用。 .您可以使用相同的ID获得它们..让我们检查我的答案
-
谢谢!这就是问题所在。我在两个迁移(tickets 和 order_lines)中都使用了带有引用的外键,正如你所说,一个就足够了。最后一个问题:如果将外键与 Ticket 或 Order_lines 中的引用一起放置会有所不同吗?再次感谢您的所有回答。
-
也许这可能是循环引用错误的一个很好的例子。要回答您的问题,请注意外键不能引用(尚)不存在的列。这两个表中哪一个具有首先创建的记录?另一个具有最低优先级或您可以认为是可选的表应该是持有外键的表。
标签: php laravel eloquent migrate