Laravel error with foreign key - laravel-5

When I'm trying to set a relation between two tables I receive the error:
D:\wamp\www>php artisan migrate Migration table created successfully.
[Illuminate\Database\QueryException] SQLSTATE[HY000]: General
error: 1215 Cannot add foreign key constraint (SQL: alter table
rittenregistratie add co nstraint
rittenregistratie_karakterritid_foreign foreign key (karakterritid)
references karakterrit (id) on d elete cascade)
[PDOException] SQLSTATE[HY000]: General error: 1215 Cannot add
foreign key constraint
D:\wamp\www>
This is my migration rittenregistratie (it's dutch) :
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRittenregistratieTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('rittenregistratie', function (Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->timestamps('datum');
$table->integer('beginstand');
$table->integer('eindstand');
$table->text('van');
$table->text('naar');
$table->text('bezoekadres');
$table->text('geredenroute');
$table->integer('karakterritid')->default(1);
$table->text('toelichting');
$table->integer('kilometerszakelijk');
$table->integer('kilomteresprive');
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('karakterritid')
->references('id')
->on('karakterrit')
->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('rittenregistratie');
}
}
This is where I want to relate to:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateKarakterritTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('karakterrit',function(Blueprint $table)
{
$table->increments('id');
$table->text('rit');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('karakterrit');
}
}
What is am I doing wrong?

Related

Laravel - 1215 Cannot add foreign constraint

I am trying to link up to three tables together but when I run my migration (using artisan) I keep getting an error:
General error: 1215 Cannot add foreign key constraint (SQL: alter table stores add constraint stores_sale_id_foreign foreign key (sale_id) references bikes (id))
Here is my migration file for stores:
class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->integer('sale_id')->unsigned();
$table->timestamps();
});
Schema::table('stores', function ($table){
$table->foreign('sale_id')->references('id')->on('bikes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}
store model:
class Store extends Model {
use HasFactory;
protected $table = 'stores';
protected $fillable = ['store_name', 'city', 'manager', 'sale_id'];
}
Edit:
bikes migration:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateBikesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('bikes', function (Blueprint $table) {
$table->increments('id');
$table->string('make');
$table->string('model');
$table->string('category');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('bikes');
}
}
Instead of increments try $table->id()or $table->bigIncrements('id') for both tables.
Because the id column will then have the right type.
You will also need to set your foreign key column to $table->unsignedBigInteger('sale_id'); to set the right column type fore the foreign constraint.
And you will have to make sure that your bikes migration runs before your stores migration.
try this,
class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->integer('sale_id')->unsigned()->nullable();
$table->timestamps();
$table->foreign('sale_id')->references('id')->on('bikes')->onDelete('cascade')->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}
Use this code
class CreateStoresTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stores', function (Blueprint $table) {
$table->increments('id');
$table->string('store_name');
$table->string('city');
$table->string('manager');
$table->unsignedInteger('sale_id')->nullable();
$table->foreign('sale_id')->references('id')->on('bikes')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('stores');
}
}
Note: Make sure there should not be a mismatch in foreign key field types.
Either change original migration from increments() to just
bigIncrements()
Or in your foreign key column do unsignedBigInteger() instead of unsignedInteger().

How to build the database migration properly?

I'm setting up a laravel project (I'm beginner) to manage customers (a customer has many contracts and a contract has many different products). And I want to implement a CRUD method and generate pdf but I have an issue at the beginning, when I migrate my database. (this is the beginning so I guess it will hard for me...)
I wrote all my migrations (customer + contracts + products) and migrate them
customer (clients):
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Clients extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->Increments('id');
$table->string('name');
$table->string('company');
$table->string('email', 50);
$table->string('phone', 15);
$table->string('adress1', 50);
$table->string('adress2', 50);
$table->string('adresse3', 50);
$table->string('pays', 20);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('clients');
}
}
Contracts (contrats)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Contrats extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
/* $table->unsignedBigInteger('clients_name');
$table->foreign('name')->references('name')->on('Clients'); */
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('contrats');
}
}
and products (produits)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Produits extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('produits', function (Blueprint $table) {
$table->Increments('id');
$table->foreign('name');
$table->string('description', 20);
$table->double('price');
$table->double('taxes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('produits');
}
}
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.03 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.02 seconds)
Migrating: 2019_10_15_131435_clients
Migrated: 2019_10_15_131435_clients (0.01 seconds)
Migrating: 2019_10_15_131454_contrats
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'name' doesn't exist in table (SQL: alter table contrats add constraint contrats_name_foreign foreign key (name) references Clients (name))
at
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'name' doesn't exist in table")
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
2 PDOStatement::execute()
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
Please use the argument -v to see more details.
I expect to get a good migration to going ahead with this project
Thanks in advance for your help, cheers.
The foreign key column format must match the format of the column it's referencing on the other table, so instead of unsignedBigInteger, it should be string
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
/* $table->unsignedBigInteger('clients_name'); */
$table->string('name');
$table->foreign('name')->references('name')->on('clients');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
Tho it's highly recommended that you reference the primary key id instead
Proper way
Eloquent will make use of naming conventions to make proper relationships with less explicit code
clients
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateClientsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('company');
$table->string('email', 50);
$table->string('phone', 15);
$table->string('adress1', 50);
$table->string('adress2', 50);
$table->string('adresse3', 50);
$table->string('pays', 20);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('clients');
}
}
contrats
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContratsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('contrats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('contrats');
}
}
produits
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProduitsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('produits', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients');
$table->string('description', 20);
$table->double('price');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('produits');
}
}
Hope this helps
Bon Courage :)
write your function up for contrats migration like this
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate')->index();
$table->date('enddate')->index();
$table->timestamps();
});

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint in laravel

can someone please help me with this one? I'm new to Laravel and when I try to do:
php artisan migrate
I get the error:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table posts add constraint posts_author_id_foreign foreign key (author_id) references users (id) on delete restrict)
and this is the post table content:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('author_id')->unsigned();
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt');
$table->text('body');
$table->string('image')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
I have noticed that when I comment this line:
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
the error is gone, so I guess the problem is in that line. So, can someone please tell me what will be the correct syntax or how to fix it?
The column data type must be the same on both tables for the foreign key to work. By default, the users id column is:
$table->bigIncrements('id');
Therefore, you need to use bigInteger for your posts migration:
$table->bigInteger('author_id')->unsigned();
Try to change the foreign ko to unsignedInteger
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('author_id');
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict');
$table->string('title');
$table->string('slug')->unique();
$table->text('excerpt');
$table->text('body');
$table->string('image')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}

Laravel Migration: get error when i want to add foreign key

I'm trying to create foreign keys in Laravel however when I migrate my table using "artisan" I am thrown the following error and i do not know why:
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1215
Cannot add foreign key
constraint (SQL: alter table `positions` add constraint
`positions_car_id_foreign`
foreign key (`car_id`) references `cars` (`id`))
The table car should hava an id which is unique and to every car there are many different positions (lat and long). The car id is the foreign key.
Car migration file:
class Car extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('cars',function (Blueprint $table){
$table->integer('id')->unique();
$table->string('name');
$table->string('location');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('cars');
}
}
Postion migration file:
class Position extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('positions',function (Blueprint $table){
$table->engine = 'InnoDB';
$table->timestamps();
$table->integer('car_id')->unsigned();
$table->double('latitude');
$table->double('longitude');
});
Schema::table('positions',function (Blueprint $table) {
$table->foreign('car_id')->references('id')->on('cars');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('positions');
}
}
You have defined the foreign key relationship with cars as $table->integer('car_id')->unsigned()
So, your migration code for id field in cars table should be
$table->unsignedInteger('id')->unique() instead of $table->integer('id')->unique()

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint - Laravel

I'm trying to create a table to hold photos and link it to the ad (property id).
I'm getting this error
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
These are my migration files
2018_02_14_191609_create_property_adverts_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePropertyAdvertsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('property_adverts', function (Blueprint $table) {
$table->increments('id');
$table->string('address');
$table->string('county');
$table->string('town');
$table->string('type');
$table->string('rent');
$table->string('date');
$table->string('bedrooms');
$table->string('bathrooms');
$table->string('furnished');
$table->longText('description');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('property_adverts');
}
}
2018_02_18_165845_create_property_advert_photos_table
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePropertyAdvertPhotosTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('property_advert_photos', function (Blueprint $table) {
$table->increments('id');
$table->integer('propertyadvert_id')->nullable();
$table->foreign('propertyadvert_id')->references('id')->on('property_adverts');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('property_advert_photos');
}
}
So the
Make it unsigned because you're using increments(). And move FK constraint part to a separate closure:
public function up()
{
Schema::create('property_advert_photos', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('propertyadvert_id')->nullable();
$table->timestamps();
});
Schema::table('property_advert_photos', function (Blueprint $table) {
$table->foreign('propertyadvert_id')->references('id')->on('property_adverts');
});
}

Resources