Migration tables with different level - laravel

When I have tables with relationship (parent and child table) can I migrate them together at once or I need to migrate the child first?

You can't migrate two tables at once, the code won't run in parallel processing
And migrating the child first will cause an error
Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table database.child (errno: 150 "Foreign key constraint is incorrectly formed")
So you have to migrate the parent first
For example, imagine a User has a Pet (domestic animal)
We would have users table and a pets table setup
Schema::create('pets', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
If the filename for the pets migration is
2013_11_06_151235_create_pets_table.php
And the filename for the users migration is
2014_10_12_000000_create_users_table.php
You would get the error above, so you have to rename the pets table migration file to a date later than the one of users
for example
2015_11_06_151235_create_pets_table.php
Because Laravel will try to create a database table with a column referencing a column in a table that doesn't exist yet
Hope this helps

If you don't have foreign key constraints, then you can migrate in any order. If you do have a Foreign Key (FK) however, then it depends on your scheme, also then you could benefit from specifying ON UPDATE and ON DELETE rules to your tables. See the mysql docs for that.

Related

Is there an error of Laravel migrations when creating a pivot table?

I have this Laravel's migration create Shema for an standard pivot table:
Schema::create('c_l', function (Blueprint $table) {
$table->foreignId('country_id')->constrained()->onDelete('cascade');
$table->foreignId('language_id')->constrained()->onDelete('cascade');
$table->unique(['country_id', 'language_id']);
});
That creates the «c_l» pivot table, but when I go to check the table structure in phpMyAdmin (Maria DB), I get the following:
Where I am missing «c_l_country_id_foreign» in the indexes section.
So I go to check the relations view, where I find:
It seems that both FKs are present.
I am wondering if this difference
is some kind of presentation issue of phpMyadmin with no effects in
operation, or if instead,
can result in a hidden non-checking of the «country_id» FK
constraint, or
can slow down when fetching the database by «country_id», or
other
Thanks for your help in advance!

In Laravel, SQLite Foreign Keys with Set Null on Delete not working for PHPUnit test

I have added a foreign keys constraint in migration file for posts table to the user_id column. So, on delete user, I want to set the user_id column to null. So, I added this.
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('set null');
It is working on the MySQL database. But not working on SQLite PHPUnit test. I have enabled foreign key constraints for SQLite, but still not working.
Please guide How can I make it work?

How to transform an existing column in foreign key using Laravel Migrations

I'm having trouble trying to change a column type in laravel to fits it as a compatible column to be a foreign key referencing another table id fields.
I have a a schema like this:
Schema::create('person_organization', function(Blueprint $table){
...
$table->integer('organization_id');
...
});
and I want to change the field organization_id to an unsigned type, which will make it able to be a foreign key referencing the id field in the organizations table.
NOTE: Just changing the field type in the creation of the table is not an available option, because the system is running in production mode.
So we need to make a new migration to do these changes.
NOTE 2: i tried the method change as described in laravel docs, but it sticks in a query error, as following:
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') on delete cascade' at line 1 (SQL: alter table person_organization add constraint person_organization_person_id_foreign foreign key (person_id) references persons () on delete cascade)
Considering you have already installed doctrine/dbal package in your application
Now create migration php artisan make:migration your_migration_name and then in migration insert the below code.
Schema::table('persons', function(Blueprint $table) {
$table->integer('organization_id')->unsigned()->index()->change();
$table->foreign('organization_id')->references('id')->on('organizations')-
>onDelete('cascade');
})
now run command php artisan migrate and now your are done.
Happy coding...
From Laravel 5.6 docs:
Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file.
composer require doctrine/dbal
Then create the migration:
php artisan make:migration add_organization_foreign_to_persons_table --table=persons
And:
Schema::table('persons', function (Blueprint $table) {
$table->unsignedInteger('organization_id')->change();
$table->foreign('organization_id')->references('id')->on('organizations');
});
$table->integer('organization_id')->unsigned();
$table->foreign('organization_id')->references('id')->on('organizations')->onDelete('cascade');

Laravel 5 Eloquent bidirectional foreign key migrations

I've and interesting scenario, I would like to implement in Laravel 5. I have 2 tables.
Users ( Holds the sites users )
Media ( Holds the sites images, documents, svg-s, etc... )
My technical constraints are:
Every user has a profile picture and only one profile picture
Every media has an Author
These contraints I interpret as logical columns on
Users table has a column
- profile_image_id (reference to the Media table id column)
Media table has a column
- author_id (reference to the Users table id column)
This works out well, but becomes problematic when I want to use artisan migrations.
my migrations run in this order
Migrating USERS table
Migrating MEDIA table
My migrations have foreign keys being set as
USERS MIGRATION
$table->foreign('profile_image_id')->references('id')->on('media')->onDelete('restrict')->onUpdate('cascade');
MEDIA MIGRATION
$table->foreign('author_id')->references('id')->on('users')->onDelete('restrict')->onUpdate('cascade');
The command I use is
php artisan migrate:refresh --seed
The problem is that when creating the users table, the media table doesn't exist as of yet. And when trying to add the foreign key relation to media table, it produces a SQL error that the media table doesn't exist.
What I did?
I created a function on Users table migration that I ran after the seeding functions had finished
/**
* Veyzon
*
* To be run after the regular run functions on all tables
* have run
*/
public static function delayed_up() {
Schema::table('users', function (Blueprint $table) {
$table->foreign('profile_image_id')->references('id')->on('media')->onDelete('restrict')->onUpdate('cascade');
});
}
This worked out fine and dandy, but when remigrating, then Media table will not delete due to the fact that the user table still has records, where there are profile_image_id-s with values.
Now I thought I will add a few lines of code to the Media tables "down" function, that will set all the USERS table profile_media_id-s to null, but I don't really like this as this seems to tie my separate migration files together and when I declare this as architecturally normal, then this will become a bad practice.
What would you guys do, to create bidirectional One-to-One foreign key relations and integrate them into Laravel migrations?
Easy way to make foriegn key in laravel
public function up()
{
Schema::create('bank_user_details', function (Blueprint $table) {
$table->foreign('country')->references('id')->on('country')
->onUpdate('cascade')->onDelete('cascade');
});
}

Creation of table columns using artisan migration

Using artisan migrate command, i am trying to create the table. users table is created but not the columns. What could I check ?
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
public function up()
{
Schema::create('users', function($table)
{
$table->increments('id');
$table->string('email');
$table->string('password');
$table->timestamps();
});
}
Upon running the above migration file, the table and its columns are successfully created in the database. If you see that the users table is created but not the columns in it, then you might not be looking properly.
I am writing the following answer on my assumption that you're very new to web development also and might not be acquainted with the tools yet.
I assume you're using phpMyAdmin to view your database. If you go to your database and then the users table, you'll be in the Browse tab. Of course, it will be empty because there are no data inserted in the users table, but if you click the Structure tab, then you can view the schema of your users table and see that the columns are created.

Resources