我正在向 Tickets 表添加一个外键。另一个表是 ticket_statuses。
在 artisan 中,我执行了这个命令:php artisan make:migration add_ticket_status_to_tickets_table
这是迁移文件中的代码:
class AddTicketStatusToTicketsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('tickets', function ($table) {
$table->integer('ticket_status_id')->unsigned();
$table->foreign('ticket_status_id')->references('id')->on('ticket_statuses')->onDelete('cascade');
});
}
}
在那之后,我尝试建立关系。这是我在 Tickets 模型 中的代码:
class Ticket extends Model
{
// Ticket __belongs_to__ Ticket Status
public function ticket_status()
{
return $this->belongsTo('App\TicketStatus');
}
}
在 artisan 中,我执行了 php artisan migrate 但是我遇到错误
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`idealcrmalphadb`.`#sql-4ea_1ce`, CONSTRAINT `tickets_ticket_status_id_foreign` FOREIGN KEY (`ticket_status_id`) REFERENCES `tickets` (`id`) ON DELETE CASCADE) (SQL: alter table `tickets` add constraint tickets_ticket_status_id_foreign foreignkey (`ticket_status_id`) references `tickets` (`id`) on delete cascade)
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`idealcrmalphadb`.`#sql-4ea_1ce`, CONSTRAINT `tickets_ticket_status_id_foreign` FOREIGN KEY (`ticket_status_id`) REFERENCES `tickets` (`id`) ON DELETE CASCADE)
我在模型部分弄错了吗?请帮忙
最佳答案
检查你的迁移表名和引用表名。你这里有误。
更新:
看来您的门票表中已有数据。如果是这样,你现在就可以试试
$table->integer('ticket_status_id')->unsigned()->nullable();
关于php - 如何在 Laravel 5.1 Integrity constraint violation : 1452? 中添加外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123300/