I have a problem while migrating
Migration File
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterTableMm extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('downloads', function($table){
$table->engine = 'InnoDB';
$table->increments('id')->unsigned();
$table->string('title',255);
$table->string('count',45)->default(0);
$table->timestamps();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
Schema::table('marketing_materials', function($table)
{
$table->string('download_total', 45 )->default(0);
$table->integer('download_id')->unsigned();
$table->foreign('download_id')->references('id')->on('downloads');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('users', function($table)
{
$table->dropForeign('users_user_id_foreign');
});
Schema::drop('downloads');
Schema::table('marketing_materials', function($table)
{
$table->dropForeign('marketing_materials_download_id_foreign');
});
Schema::table('marketing_materials', function($table)
{
$table->dropColumn('download_total');
$table->dropColumn('download_id');
});
}
}
Error Message
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`distributor-local`.`#sql-668_3d`, CONSTRAINT `marketing_mater
ials_download_id_foreign` FOREIGN KEY (`download_id`) REFERENCES `downloads` (`id`)) (SQL: alter table `marketing_materials` add constraint marketing_materials_download_id_foreign fo
reign key (`download_id`) references `downloads` (`id`))
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`distributor-local`.`#sql-668_3d`, CONSTRAINT `marketing_mater
ials_download_id_foreign` FOREIGN KEY (`download_id`) REFERENCES `downloads` (`id`))
I have all the required tables
users
marketing_materials
I just recently migrate my downloads table
Can someone tell me what did I do wrong ?
The part that confuse me the most of that error message is that, all the contents are added the database fine. See the picture below
I also alter my marketing_materials table, and that's also work.
Should I just ignore the error message ???
Related
I am trying to rename a foreign column. So I write the following code:
Schema::table('floor_plans', function (Blueprint $table) {
$table->dropForeign(['unit_type_id']);
$table->renameColumn('unit_type_id', 'utd_id');
$table->foreign('utd_id')
->references('id')
->on('unit_type_details')
->onDelete('cascade');
});
But it throws
Doctrine\DBAL\Schema\SchemaException : There is no column with name 'unit_type_id ' on table 'floor_plans'.
at D:\wamp64\www\amenity\vendor\doctrine\dbal\lib\Doctrine\DBAL\Schema\SchemaException.php:85
81| * #return \Doctrine\DBAL\Schema\SchemaException
82| */
83| public static function columnDoesNotExist($columnName, $table)
84| {
> 85| return new self(
86| sprintf("There is no column with name '%s' on table '%s'.", $columnName, $table),
87| self::COLUMN_DOESNT_EXIST
88| );
89| }
Then I tried by turning foreign checks off:
DB::statement('SET FOREIGN_KEY_CHECKS=0');
$table->dropForeign(['unit_type_id']);
$table->renameColumn('unit_type_id ', 'utd_id');
DB::statement('SET FOREIGN_KEY_CHECKS=1');
But same error, the column not found.
Then I tried to drop foreign with exact ForeignKeyConstraint as :
DB::statement('SET FOREIGN_KEY_CHECKS=0');
$table->dropForeign('floor_plans_unit_type_id_foreign');
$table->renameColumn('unit_type_id', 'utd_id');
DB::statement('SET FOREIGN_KEY_CHECKS=1');
$table->foreign('utd_id')
->references('id')
->on('unit_type_details')
->onDelete('cascade');
Still the same error.
I then even tried with Raw SQL as:
DB::statement("ALTER TABLE floor_plans
DROP FOREIGN KEY `floor_plans_unit_type_id_foreign`,
ADD CONSTRAINT `floor_plans_unit_type_detail_id_foreign` FOREIGN KEY (`unit_type_detail_id`) REFERENCES `unit_type_details` (`id`)");
And this gives me the following error:
SQLSTATE[42000]: Syntax error or access violation: 1091 Can't DROP 'floor_plans_unit_type_id_foreign'; check that column/key exists (SQL: ALTER TABLE floor_plans
DROP FOREIGN KEY `floor_plans_unit_type_id_foreign`,
ADD CONSTRAINT `floor_plans_unit_type_detail_id_foreign` FOREIGN KEY (`unit_type_detail_id`) REFERENCES `unit_type_details` (`id`))
And here is the screenshot of the table.
All I want is to rename unit_type_id to unit_type_detail_id.
#PS: the table is not empty. And, I am happy to run even if you provide me the raw MySQL query.
Their is an additional space on unit_type_id.
Schema::table('floor_plans', function (Blueprint $table) {
$table->dropForeign(['unit_type_id']);//note foreign key already dropped so also you have to make this line also as comment when you test.
//$table->renameColumn('unit_type_id ', 'utd_id');//remove this space and try again
$table->renameColumn('unit_type_id', 'utd_id');//after remove space
$table->foreign('utd_id')
->references('id')
->on('unit_type_details')
->onDelete('cascade');
});
I have a problem running the migration of my Laravel project. When I run artisan migrate, it stops in the foreign key. Can someone help me with this? I tried the solution on the other similar questions but it does not work.
Error Message: SQLSTATE[HY000]: General error: 1005 Can't create table.
airways.#sql-4588_cfb (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table flights add constraint flights_airport_departure_foreign
foreign key (airport_departure) references airports (airport_code) on delete cascade)
flights_table.php
public function up()
{
Schema::create('flights', function (Blueprint $table) {
$table->integer('flight_number')->primary();
$table->string('airline');
$table->integer('airport_departure')->unsigned();
$table->string('departure_time');
$table->integer('airport_arrival')->unsigned();
$table->string('arrival_time');
$table->string('flight_duration');
$table->timestamps();
});
Schema::table('flights', function($table) {
$table->foreign('airport_departure')
->references('airport_code')->on('airports')
->onDelete('cascade');
$table->foreign('airport_arrival')
->references('airport_code')->on('airports')
->onDelete('cascade');
});
}
airports_table.php
public function up()
{
Schema::create('airports', function (Blueprint $table) {
$table->integer('airport_code')->primary();
$table->string('airport_name');
$table->string('airport_location');
$table->string('airport_state');
$table->timestamps();
});
}
Your foreign key column types are wrong. You're not setting the airport_code as an unsigned integer but airport_departure and airport_arrival are expecting unsigned integers. Also you'll need to create the airports table before creating flights table, not the other way 'round as suggested by others.
Rollback your migration, change the order of migration i.e if the airport table is 2014_10_12_0000 and the flights_table is 2014_10_12_00001, change airport table to 0002.
i have reply_qs table and postqs table.Postqs_id is foreign key in reply_qs table.when i tried to save the reply_qs form data in database,its showed this error.
ERROR:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a
child row: a foreign key constraint fails (fyp2.reply_qs, CONSTRAINT
reply_qs_postqs_id_foreign FOREIGN KEY (postqs_id) REFERENCES postqs
(id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into reply_qs
(reply, updated_at, created_at) values (saann, 2017-09-22 15:35:03,
2017-09-22 15:35:03))
how i can solve it? and please explain why im getting this error.
reply_qs model :
protected $table = 'reply_qs';
protected $fillable = ['reply'];
public function postqs(){
return $this->hasMany('App\Postqs');
}
postqs model :
public function reply_qs(){
return $this->hasMany('App\Reply_qs');
}
store function:
public function store(Request $request){
$data = $request->all();
$postqs=($request->id);
$reply=Reply_qs::create($data);
$reply->postqs($id);
}
migration:
Schema::create('reply_qs', function (Blueprint $table) {
$table->increments('id')->unique();
$table->text('reply');
$table->timestamps('date');
});
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
Schema::table('reply_qs',function(Blueprint $table)
{
$table->integer('postqs_id')->unsigned();
$table->foreign('postqs_id')->references('id')->on('postqs') -
>onDelete('cascade')->onUpdate('cascade');
});
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Your relationships are not correct.
Your Reply_qs model should have this relationship with Postqs
public function postqs()
{
return $this->belongsTo(Postqs::class);
}
Your store function does not look correct and should look something like this
public function store( Request $request )
{
$reply = new Reply_qs();
$reply->text = $request->get('text');
$reply->postqs_id = $request->get('postqs_id');
$reply->save();
}
In your store method, it looks like you are trying to associate the parent Postqs object with the Reply_qs.
You would do this like so
$reply->associate($post);
You need to pass the object and not the id
If you are still struggling with this double check your foreign keys are matching correctly, you may need to implement the association like so
public function postqs()
{
return $this->belongsTo(Postqs::class, 'postqs_id', 'id);
}
I'm trying to write a laravel database migration but I'm getting the following error about a foreign key:
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table (SQL: alter table `subcategories` add constraint subcategories_category_id_foreign foreign key (`category_id`) references `categories` (`id`))
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'category_id' doesn't exist in table
The categories and subcategories tables do get created but the foreign key doesn't. Here's my migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoryTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function ($table) {
$table->increments('id')->unsigned();
$table->string('name')->unique();
});
Schema::create('subcategories', function ($table) {
$table->increments('id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
$table->string('name')->unique();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('categories');
Schema::drop('subcategories');
}
}
Any ideas? Thanks!
You should create column before creating a foreign key:
$table->integer('category_id')->unsigned();
$table->foreign('category_id')->references('id')->on('categories');
Documentation: http://laravel.com/docs/5.1/migrations#foreign-key-constraints
Laravel 7, 8
As Limon Monte mentioned firstly create column then add foreign key constraints
$table->foreignId('category_id');
$table->foreign('category_id')->references('id')->on('categories');
Integer didn't work for me. Rather, I used bigInteger to create foreign key:
$table->bigInteger('category_id')->unsigned()->index()->nullable();
$table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
I forgot to add ->get() to the methods I called.
After creatin multiple migrations in my project, I wanted to rollback to update a few things but suddenly I got this error when I tried to drop projects table. I double checked the foreign key constrains but I can't find the error.
[Illuminate\Database\QueryException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or upda
te a parent row: a foreign key constraint fails (SQL: drop table `projects`
)
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or upda
te a parent row: a foreign key constraint fails
Here are my migrations:
1.create table users:
public function up()
{
Schema::create('users', function(Blueprint $table)
{
$table->increments('id');
$table->string('first_name');
$table->string('last_name');
$table->string('email', 50)->unique();
$table->string('password', 60);
$table->string('password_temp', 60);
$table->string('code', 60);
$table->boolean('active');
$table->string('remember_token', 100);
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
2.create clients table:
public function up()
{
Schema::create('clients', function(Blueprint $table)
{
$table->increments('id');
$table->integer('user_id')->unsigned()->index()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::drop('clients');
}
3.create projects table:
public function up()
{
Schema::create('projects', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->integer('status');
$table->integer('client_id')->unsigned()->index()->nullable();
$table->foreign('client_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
public function down()
{
Schema::drop('projects');
}
In the last migration, what could possibly be the mistake I am doing?! I face no trouble when migrating but it appears only when I rollback to add any changes.
Any idea why this happens?
Use this in down function.
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::dropIfExists('tableName');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
If there are only 3 tables above mentioned, there is no issue in your migration as I have tried it myself with
php artisan migrate
to create the tables and
php artisan migrate:rollback
to rollback.
One thing that I know is Laravel is going to assume the sequence of the migration based on the migration file timestamp.
Therefore, I am quite sure there is another table that has a foreign key reference to the projects tables that has not been dropped as the error messsage is (SQL: drop table projects)
Try to use php artisan tinker and then Schema::drop('some_table_name'); where some_table_name is the table that has reference to projects table, then drop the projects table again.
When you use foreign keys in your tables you need to remove those using the dropForeign method before you drop your table, else you will run into the integrity constraint issues you are currently getting.
public function down()
{
Schema::table('projects', function(Blueprint $table) {
$table->dropForeign('projects_client_id_foreign');
});
Schema::drop('projects');
}
This problem is commonly created by editing/adding to existing migrations.
Either create new migration files when dealing with foreign keys or be prepared to potentially dump/drop your entire db and refresh.