我正在给Tickets Table添加一个外键。另一个表ticket_statuses。
在artisan中,我执行了以下命令: php artisan make:迁移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 Model中的代码:
class Ticket extends Model
{
// Ticket __belongs_to__ Ticket Status
public function ticket_status()
{
return $this->belongsTo('App\TicketStatus');
}
}
在artisan中,我执行了php artisan迁移,但我遇到了一个错误
[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)
我是不是在模型部分搞错了?请帮帮忙
检查您的迁移表名称和引用表名称。您在这里有错误。
UPD:
看起来您的工单表中已经有数据了。如果有,您现在可以尝试
$table->integer('ticket_status_id')->unsigned()->nullable();