The Problem
I want to add foreign keys to tables. When I run my first migration create_posts_table that looks like this:
Schema::create('posts', function(Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->unsignedInteger('user_id')->index();
// . . .
});
Schema::table('posts', function(Blueprint $table)
{
$table->foreign('user_id')->references('id')
->on('users')->onDelete('cascade');
});
The following error is thrown:
[Illuminate\Database\QueryException] SQLSTATE[HY000]:
General error: 1215 Cannot add foreign key constraint (SQL: alter table
posts add constraint posts_user_id_foreign foreign key (user_id) references users (id) on delete cascade)
This is caused because the users table is not created yet, hence the failure to create the users' referencing foreign key on the posts table.
Possible Solution
The solution to this problem would be to add the foreign keys with a new migration after all of the tables had been created. However, it seems clunky to me.
The question
How can I define the foreign keys inside their respective tables' migrations, instead of adding them separately with the different migration after all of the tables had been created?
You can perform multiple migrations in the same migration file. If you have a posts table where you want a foreign key to the users table, but the users table does not yet exist, you either have to do it in the users table migration file after the users table has been created - or you have to do a separate migration, like you said. You can't "save" instructions for later in migrations.
In laravel way is keeping separate migration files for different tables with indexing, primary key & foreign keys.....
CreateUsersTable
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password', 60);
$table->enum('status', ['0', '1'])->default('0');
$table->rememberToken();
$table->nullableTimestamps();
$table->unique('email');
});
}
public function down()
{
Schema::drop('users');
}
}
CreatePostsTable
class CreatePostsTable extends Migration
{
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
}
public function down()
{
Schema::drop('posts');
}
}
Related
I have posts table:
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('imid');
$table->string('name');
$table->text('body');
$table->timestamps();
});
and
images table:
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('imid');
$table->string('name')->nullable();
$table->longText('image_path')->nullable();
$table->timestamps();
});
I am trying to add a foreign field to existing posts table in a separate migration:
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->foreign('imid')->references('imid')->on('images')->onDelete('cascade');
});
}
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('imid');
});
}
But when I run
php artisan migrate
I get error:
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `posts` add constraint `posts_imid_foreign` foreign key (`imid`) references `images` (`imid`) on delete cascade)
It seems I do it right. What am I missing here?
Check that both your tables have the columns for which you create the foreign key (imid) and that these columns have the same types. You can use the following commands to do this:
DESCRIBE posts;
DESCRIBE images;
Next, check if posts table has no imid values which point to non-existing records in the images table (If they are - connect them to existing ones or remove them)
SELECT posts.id, posts.imid FROM posts
LEFT JOIN images ON posts.imid = images.imid
WHERE images.id IS NULL;
Make sure your tables are using InnoDB engine
SHOW TABLE STATUS WHERE name = 'posts';
if Engine != InnoDB then run:
ALTER TABLE posts ENGINE = InnoDB;
Finally, I suggest that you change the down method of your migration so that it does the reverse of the up method:
Schema::table('posts', function (Blueprint $table) {
$table->dropForeign('posts_imid_foreign');
});
I'm trying to create foreign keys in Laravel however when I migrate my table using artisan i am thrown the following error:
SQLSTATE[HY000]: General error: 1005 Can't create table `bright`.`carts` (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `carts` add constraint `carts_product_id_foreign` foreign key (`product_id`) references `products` (`id`) on delete cascade)
My migration code is as so: carts migration file
public function up()
{
Schema::create('carts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('product_id')->unsigned();
$table->integer('customer_id')->unsigned();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->foreign('customer_id')->references('id')->on('customers')->onDelete('cascade');
$table->string('quantity');
});
}
products migration file
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('unit');
$table->decimal('price', 6, 3);
$table->string('img_url');
$table->string('description');
$table->integer('sold');
$table->integer('in_stock');
});
}
customers migration file
public function up()
{
Schema::create('customers', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('first_name');
$table->string('last_name');
$table->string('phone_number');
$table->string('address');
$table->string('zip')->nullable();
$table->string('email')->unique();
$table->string('user_name')->unique();
$table->string('password');
});
}
Any ideas as to what I've done wrong, I want to get this right now, as I've got a lot of tables I need to create e.g. carts, products, customers. Ideally I want to create carts table which hold this data with the foreign keys, i..e product_id and cart_id
Try using this structure.
$table->foreignIdFor(Product::class);
$table->foreign('product_id')->references('id')->on('products');
$table->foreignIdFor(Customer::class);
$table->foreign('customer_id')->references('id')->on('customers');
Also make sure, your products and customers migrations run before your carts migrations, and your models are imported to your migrations.
You can use like this.
$table->unsignedBigInteger('product_id')->nullable();
$table->foreign('product_id')->references('id')->on('products');
$table->unsignedBigInteger('customer_id')->nullable();
$table->foreign('customer_id')->references('id')->on('customers');
I have created a table called 'users'.There are tables called 'companies','designations','departments'.I want to add company_id,designation_id,department_id columns to users table as foreign keys.
I tried this but it didn't work
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('department_id');
$table->integer('company_id');
$table->integer('designation_id');
$table->foreign('department_id')->references('id')->on('departments')->onDelete('restrict')->onUpdate('restrict');
$table->foreign('company_id')->references('id')->on('companies')->onDelete('restrict')->onUpdate('restrict');
$table->foreign('designation_id')->references('id')->on('designations')->onDelete('restrict')->onUpdate('restrict');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['department_id','company_id','designation_id']);
});
}
When I migrate the migration it shows this error.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General
error: 1005 Can't create table lanwadb.users (errno: 150 "Foreign
key constraint is incorrectly formed") (SQL: alter table users add
constraint users_department_id_foreign foreign key (department_id)
references departments (id) on delete restrict on update restrict)
Designation migration as follows,
public function up()
{
Schema::create('designations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestampsTz();
});
}
Department migration as follows,
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('company_id');
$table->timestampsTz();
});
}
```
To make relationship the foreign key field should be indexed. Here you have three columns you want to use as foreign key 'company_id', 'department_id' and 'designation_id'. In Laravel migration you can use unsigned() function to index them.
Example:
$table->integer('department_id')->unsigned();
$table->integer('company_id')->unsigned();
$table->integer('designation_id')->unsigned();
There is another function called unsignedInteger() by which you can make a column both Integer and Unsigned.
$table->unsignedInteger('department_id');
$table->unsignedInteger('company_id');
$table->unsignedInteger('designation_id');
use this:
$table->integer('department_id')->unsigned()->nullable();
$table->integer('company_id')->unsigned()->nullable();
$table->integer('designation_id')->unsigned()->nullable();
$table->foreign('department_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('company_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('designation_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');
I have two tables like this
Books
id|book_name|writter_id
1|Artemis|1
Writters
id|writter_name
1|Jane Doe
both of the tables have a relationship like this
Book model return $this->belongsTo('App\Writter', 'writter_id');
Writter model return $this->hasMany('App\Book', 'writter_id');
books.index.blade.php
<p>{{ $book->writter->writter_name }}</p>
create books
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->string('book_name', 100)->unique();
$table->integer('writter_id')->unsigned();
$table->timestamps();
});
}
create writter
public function up()
{
Schema::create('writters', function (Blueprint $table) {
$table->increments('id');
$table->string('writter_name', 100);
$table->timestamps();
});
// Set Foreign Key
Schema::table('books', function (Blueprint $table) {
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('cascade')
->onUpdate('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
// Drop Foreign Key di kolom id_penulis di table books
Schema::table('books', function(Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
});
Schema::drop('writters');
}
Every time i delete the writters (for an example like jane doe above) the books data still have the writter_id So the index view throw me an error.
Is it possible to delete the data/row from the writters table, and delete the writter_id on the books in the same time?
Edit your books table migration and add foreign keys
$table->integer('writter_id')->unsigned()->nullable();
Schema::table('books', function($table) {
$table->foreign('writter_id')->references('id')->on('writters')->onDelete('set null');
});
As you see it sets null on writter delete
For make youre migration file, do you use foreign key ?
With foreign key you can add a method for on Delete.
Foreign key Documentation
migration.php
$table->integer('writter_id')->unsigned();
$table->foreign('writter_id)->references('id')->on('writters)->onDelete('cascade');
It's will be work
If you haven't set up foreign keys on your tables, removing a row from a table won't update the column referencing to that row.
To solve this we can set up foreign keys with the schema builder.
You can create a new migration file or modify your existing migrations if you don't care about your current database values.
Create a new migration file with php artisan make:migration. Inside that file, use these methods (don't forget to run composer require doctrine/dbal before running the migration):
public function up() {
// Remove current foreign keys and index.
Schema::table('books', function (Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
$table->dropIndex('books_writter_id_foreign');
});
// Add new foreign and allow books to now have a writter by using `NULL`.
Schema::table('books', function (Blueprint $table) {
$table->integer('writter_id')->unsigned()->nullable()->change(); // Before changing a column, be sure to add the doctrine/dbal dependency to your composer.json file.
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('SET NULL');
});
}
public function down() {
// Revert to previous values.
Schema::table('books', function (Blueprint $table) {
$table->dropForeign('books_writter_id_foreign');
$table->dropIndex('books_writter_id_foreign');
$table->integer('writter_id')->unsigned()->change();
$table->foreign('writter_id')
->references('id')
->on('writers')
->onDelete('cascade')
->onUpdate('cascade');
});
}
Using ->onDelete('SET NULL') on the foreign key will set the value to NULL when the referenced value is deleted from the referenced table.
In your blade file you can now check if the book have a writer before outputting it:
#if ($book->writter_id)
<p>{{ $book->writter->writter_name }}</p>
#endif
I have 3 models: User , ChangeMoney and CurrencyType, I have simple relationship with User and ChangeMoney and I want to add another relationship with ChangeMoney table with CurrencyType, but I get this error:
D:\xampp\htdocs\epay-pro>php artisan migrate
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
: alter table `change_money` add constraint change_money_currency_id_foreig
n foreign key (`currency_id`) references `currency_type` (`id`))
current my migration is:
Schema::create('change_money',function(Blueprint $table){
$table->increments('id');
$table->tinyInteger('currency_type');
$table->string('current_money');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('currency');
$table->timestamps();
});
and I don't have any problem, now I want to add other foreign key to CurrencyType table such as:
Schema::create('change_money',function(Blueprint $table){
$table->increments('id');
$table->tinyInteger('currency_type');
$table->string('current_money');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('currency_id')->unsigned();
$table->foreign('currency_id')->references('id')->on('currency_type');
$table->timestamps();
});
currency_type table migration:
Schema::create('currency_type',function(Blueprint $table){
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('currency_type','50');
$table->char('currency_symbol','1');
$table->timestamps();
});
Migrations in Laravel runs in order. I don't now your migrations order, but I think that your change_money migration is running first than your currency_type migration. So when the aplication try to add a foreign key in ChangeMoney table to CurrencyType table, the CurrencyType table not exist yet.
Try to create a new migration to add just the relationship between ChangeMoney table and CurrencyType table
You have to remove data from both tables ('change_money', 'currency_type').
Or you can turn off the check of foreign keys. In MySQL, or in the phpmyadmin run this:
SET FOREIGN_KEY_CHECKS=0;
Run migration in Laravel: php artisan migrate
And then again turn on check of foreign keys:
SET FOREIGN_KEY_CHECKS=1;
PROBLEM SOLVED by split foreign key to other migration
class ForeignKeyBetweenChangeMoneyAndCurrencyType extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('change_money', function (Blueprint $table) {
$table->integer('currency_id')->unsigned();
$table->foreign('currency_id')->references('id')->on('currency_type');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('change_money', function(Blueprint $table) {
$table->dropForeign(' change_money_currency_id_foreign');
});
}
}