I have one migration to execute. And here is my code:
public function up()
{
Schema::table('students', function (Blueprint $table) {
//
$table->foreign('phone_id')->reference('id')->on('phone');
});
}
where i execute migration, it said i have an error in my sql. And i run php artisan migrate --pretend to output the sql:
alter table `students` add constraint `students_phone_id_foreign` foreign key (`phone_id`) references `phone` ()
As you can see, there is a () at the end of the sql. How does it come out?
Schema::table('students', function ($table) {
$table->integer('phone_id')->unsigned();
$table->foreign('phone_id')->references('id')->on('phones');
});
Related
When I try to run php artisan migrate:refresh --seed on my tables, it always get stuck on this one:
public function down()
{
if (Schema::hasTable('leads')) {
Schema::table('leads', function (Blueprint $table) {
$table->dropForeign('leads_dealer_id_foreign'); //this is the line
$table->dropIndex('leads_dealer_id_index');
$table->dropColumn('dealer_id');
Schema::dropIfExists('leads');
});
}
}
The error is: Base table or view not found: 1146 Table 'leads' doesn't exist (SQL: alter table leads drop foreign key leads_dealer_id_foreign)
I've commented the line that produces the error in the snippet above.
Why would it complain about the table not existing? Even if the table doesn't exist, I've wrapped everything inside Schema::hasTable('leads') so it shouldn't even execute that line.
What causes my leads table to drop early? I've looked at my other migrations and nowhere I'm dropping that table except on its own migration file.
Thanks
You must drop the foreign keys first, then drop the table. In order to do this move Schema::dropIfExists('leads'); outside the closure:
public function down()
{
if (Schema::hasTable('leads')) {
Schema::table('leads', function (Blueprint $table) {
$table->dropForeign('leads_dealer_id_foreign'); //this is the line
$table->dropIndex('leads_dealer_id_index');
$table->dropColumn('dealer_id');
});
Schema::dropIfExists('leads');
}
}
Hi there is have looked for solutions on Stack an couldn't solve my problem.
I am Using Laravel 7.x. At first my migrations where working properly but when i changer$table->foreignId("exp_id")->constrained("expenses")->index(); to $table->foreignId("fk_expense")->constrained("expenses")->index();, it started to show this error on migration
SQLSTATE[HY000]: General error: 1005 Can't create table `edmart`.`cancelled_ex
ps` (errno: 121 "Duplicate key on write or update") (SQL: alter table `cancelled
_exps` add constraint `1` foreign key (`fk_expense`) references `expenses` (`id`
))
Bellow are the migration file for expenses
public function up(){
Schema::create('expenses', function (Blueprint $table) {
$table->id();
$table->foreignId("user_id")->constrained("users")->index();
$table->string("desc");
$table->string("amount");
$table->string("status");
$table->timestamps();
});
}
cancelled expenses migration files
public function up()
{
Schema::create('cancelled_exps', function (Blueprint $table) {
$table->id();
$table->foreignId("fk_expense")->constrained("expenses")->index();
$table->string('viewed');
$table->timestamps();
});
}
I tried to remove the database and create a new one but still it failed.
Update:
All other migrations work properly except cancelled_exps
i changed the $table->foreignId("fk_expense")->constrained("expenses")->index() to
$table->foreignId("expences_id")->constrained()
$table->index('expense_id');
I changed the foreign key column name to expense_id hence i don't
have to specify the expenses table in constrained() chained
method.
I also changed the way i was chaining the index.
The whole migration file looks like this....
public function up()
{
Schema::create('cancelled_exps', function (Blueprint $table) {
$table->id();
$table->foreignId("expense_id")->constrained();
$table->index("expense_id");
$table->string('viewed');
$table->timestamps();
});
}
This error popup:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`ltfrbr10infosystem`.`franchises`, CONSTRAINT `franchises_operator_id_foreign` FOREIGN KEY (`operator_id`) REFERENCES `operators` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
Laravel Migrration:
public function up()
{
Schema::create('franchises', function (Blueprint $table) {
$table->increments('id');
$table->integer('operator_id')->nullable()->unsigned();
$table->foreign('operator_id')->references('id')->on('operators')->onDelete('cascade')->onUpdate('cascade');
$table->string('case_number')->nullable();
$table->string('business_address')->nullable();
$table->date('date_granted')->nullable();
$table->date('expiry_date')->nullable();
$table->string('route_name')->nullable();
$table->string('deno')->nullable();
$table->integer('authorize_units')->nullable();
$table->string('remarks')->nullable();
$table->timestamps();
});
}
I have tried this but still it gives me error
$table->integer('operator_id')->nullable()->unsigned()->change();
I also tried this
$table->integer('operator_id')->unsigned()->default(null);
How do I make operator_id foreign key default to null?
If the data on your database is not important you could refresh your migrations and your database using
php artisan migrate:refresh
This will rollback and migrate all your migrations again. Make sure you wrote the down method right,
also, you migration should look like this:
public function up()
{
Schema::create('franchises', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('operator_id')->nullable();
$table->foreign('operator_id')->references('id')->on('operators')->onDelete('cascade')->onUpdate('cascade');
$table->string('case_number')->nullable();
$table->string('business_address')->nullable();
$table->date('date_granted')->nullable();
$table->date('expiry_date')->nullable();
$table->string('route_name')->nullable();
$table->string('deno')->nullable();
$table->integer('authorize_units')->nullable();
$table->string('remarks')->nullable();
$table->timestamps();
});
}
Other way to do it is creating a new migration like this:
public function up()
{
Schema::table('franchises', function (Blueprint $table) {
$table->unsignedInteger('operator_id')->nullable()->change();
});
}
I think you get this error because the record you are trying to insert contains a wrong value for the column operator_id. This value is not a correct operator id and is not null (it could be 0, "null" or empty string, ...)
Can you paste here the exact SQL query which rises this error ?
Add this inside up function and run php artisan migrate:refresh --seed
public function up(){
Schema::disableForeignKeyConstraints();
Schema::create('franchises', function (Blueprint $table) {
$table->increments('id');
$table->integer('operator_id')->unsigned()->nullable();
$table->foreign('operator_id')->references('id')->on('operators')->onDelete('cascade')->onUpdate('cascade');
$table->string('case_number')->nullable();
$table->string('business_address')->nullable();
$table->date('date_granted')->nullable();
$table->date('expiry_date')->nullable();
$table->string('route_name')->nullable();
$table->string('deno')->nullable();
$table->integer('authorize_units')->nullable();
$table->string('remarks')->nullable();
$table->timestamps();
});Schema::enableForeignKeyConstraints();}
you should use this
$table->foreign('operator_id')->references('id')->on('operators')->nullable()->onDelete('cascade')->onUpdate('cascade');
i cant figure out what im doing wrong, but everything looks ok, is giving me this errroof
Foreign key constraint is incorrectly formed
on my migrations, but i dont see any issue.
Migration table 1:
public function up()
{
Schema::create('candidate_industries', function (Blueprint $table) {
$table->increments('id');
$table->integer('candidate_id')->unsigned();
$table->foreign('candidate_id')->references('id')->on('candidates');
$table->integer('industry_id')->unsigned();
$table->foreign('industry_id')->references('id')->on('industries');
});
}
Migration number 2:
public function up()
{
Schema::create('candidate_regions', function (Blueprint $table) {
$table->increments('id');
$table->integer('candidate_id')->unsigned();
$table->foreign('candidate_id')->references('id')->on('candidates');
$table->integer('region_id')->unsigned();
$table->foreign('region_id')->references('id')->on('regions');
});
}
The issue was because "candidates" id column had a different dataType set, in my case was BigInt when i was trying to create a relation with a column of int.
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');
}
}