我正在为门票表添加外键。另一个表是 ticket_statuses 。
在工匠中,我执行了这个命令: 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');
});
}
}
之后,我尝试实现一种关系。这是我在门票模型:
中的代码class Ticket extends Model
{
// Ticket __belongs_to__ Ticket Status
public function ticket_status()
{
return $this->belongsTo('App\TicketStatus');
}
}
在工匠中,我执行 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)
我在模型部分犯了错误吗?请帮忙
答案 0 :(得分:1)
检查迁移表名称和引用表名称。你这里有错误。
UPD:
看起来你已经在故障单表中有数据了。如果是这样,你现在可以尝试
$table->integer('ticket_status_id')->unsigned()->nullable();