Laravel 迁移一对一关系错误
Posted
技术标签:
【中文标题】Laravel 迁移一对一关系错误【英文标题】:Laravel migrate one to one relationships error 【发布时间】: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 中的引用一起放置会有所不同吗?再次感谢您的所有回答。 也许这可能是循环引用错误的一个很好的例子。要回答您的问题,请注意外键不能引用(尚)不存在的列。这两个表中哪一个具有首先创建的记录?另一个具有最低优先级或您可以认为是可选的表应该是持有外键的表。 【参考方案1】:将外键定义移动到第二个函数Schema::table(...
,或者由于您在多个表之间创建约束,因此在创建所有必需的表之后,在下次迁移中添加外键。
请记住,在创建外键时,首先您需要正确形成相应的表。
附带说明,在构建数据库结构时不需要创建模型关系。之后您可以安全地创建它们...
【讨论】:
感谢您的快速回答。 gestion_concert_spectacle 是数据库的名称,我不知道为什么写成“无法创建表......但我认为问题来自外键。我按照你的指示:我删除了我的数据库并创建了另一个使用相同的名称,将所有外键和引用放在注释中,完成 php artisan migrate。所有表都已创建没有问题,我将其从 cmets 中取出并完成 php artisan migrate:refresh。我有同样的错误.. . @bruno 我的想法是将所有外键声明移动到下一个/后续迁移,并确实确保所有这些 id 都是无符号的......所以在你的迁移中首先创建所有表。然后创建下一个迁移并向该表添加外键,或为每个表创建新的迁移文件,以仅将外键添加到该特定表...【参考方案2】:我以前遇到过这样的问题。只需将$table->integer('order_line_id')->unsigned();
更改为$table->unsignedInteger('order_line_id')
;与所有其他外国 id 相同(order_id 和 ticket_id)
【讨论】:
以上是关于Laravel 迁移一对一关系错误的主要内容,如果未能解决你的问题,请参考以下文章