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().
Related
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();
});
There are two table.
Under a category there is a product name.
So, this product name must be unique.?
Like
cat1 has pro1,pro2
cat2 has pro1,pro3
Table 1 (Migration):
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('catefory', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('category');
}
}
Tbl2 (Migration )
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->foreign('category_id')->references('id')->on('category');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
For each category there should be a unique product name. How to define this in laravel migration so that each category there should be a unique products name.?
You can can create your own primary key with group of keys in your table like shown below:-
Tbl2 (Migration )
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->primary(['name', 'category_id']);
$table->string('name');
$table->foreign('category_id')->references('id')->on('category');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
This will ensure each name has a unique product/category.
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()
I wanted to delete one column, it worked but for the " rollback" it always shows up an error!
ERROR : parse error: syntax error,unexpected end of file,expectinf function (T_FUNCTION) or const ( T_CONST)
the code :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class DropBody extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('body');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->mediumText('body');
});
}
}
.
I guess you are writing reverse code, by reverse code i mean to say you have to create table fields in up function and drop columns in down function.
You should try something like this:
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->mediumText('body');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('body');
});
}
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');
});
}