I’m trying to add a relationship 1:1
between my Visitor & Contact
JavaScript
x
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class AddRelationToVisitorsDRelationToVisitorsContacts extends Migration
{
public function up()
{
Schema::table('contacts', function(Blueprint $table)
{
$table->bigInteger('visitor_id')->unsigned();
$table->foreign('visitor_id')->references('id')->on('visitors')->onDelete('cascade');
});
}
public function down()
{
Schema::table('contacts', function($table)
{
$table->dropForeign('contacts_visitor_id_foreign');
$table->dropColumn('visitor_id');
});
Schema::table('visitors', function(Blueprint $table)
{
$table->dropColumn('contact_id');
});
}
}
When run
JavaScript
php artisan migrate
Migrating: 2020_04_16_104641_update_contacts_table_04_16_2020
I kept getting
JavaScript
IlluminateDatabaseQueryException
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`bheng`.`#sql-e1_1f3`, CONSTRAINT `contacts_visitor_id_foreign` FOREIGN KEY (`visitor_id`) REFERENCES `visitors` (`id`) ON DELETE CASCADE) (SQL: alter table `contacts` add constraint `contacts_visitor_id_foreign` foreign key (`visitor_id`) references `visitors` (`id`) on delete cascade)
at vendor/laravel/framework/src/Illuminate/Database/Connection.php:670
666| // If an exception occurs when attempting to run a query, we'll format the error
667| // message to include the bindings with SQL, which will make this exception a
668| // lot more helpful to the developer instead of just the database's errors.
669| catch (Exception $e) {
> 670| throw new QueryException(
671| $query, $this->prepareBindings($bindings), $e
672| );
673| }
674|
+11 vendor frames
12 database/migrations/2020_04_16_104641_update_contacts_table_04_16_2020.php:31
IlluminateSupportFacadesFacade::__callStatic("table")
+22 vendor frames
35 artisan:37
IlluminateFoundationConsoleKernel::handle(Object(SymfonyComponentConsoleInputArgvInput), Object(SymfonyComponentConsoleOutputConsoleOutput))
Advertisement
Answer
In the latest versions of laravel the primary key is biginteger. so you might have to change this
$table->integer(‘visitor_id’)->unsigned();
with this
$table->bigInteger(‘visitor_id’)->unsigned();