Yii2 Check if foreign key exists in migration - yii2

I was creating database migration to add foreign keys. But, before that, I want to ensure that there are foreign key constraints for the given name.
$this->addForeignKey('fk-product-user_id', '{{%product}}', 'user_id', '{{%user}}', 'id');
How can I check if there is already a foreign key named fk-product-user_id exists?

To check the foreign key constraints before adding foreign key. Just fetch the table schemas and check from that.
public $tableName = '{{%product}}';
/**
* {#inheritdoc}
*/
public function safeUp()
{
$tableSchema = Yii::$app->db->schema->getTableSchema($this->tableName);
if (!isset($tableSchema->columns['user_id'])) {
$this->addColumn($this->tableName, 'user_id', $this->integer()->after('id'));
}
if (array_key_exists('fk-product-user_id', $tableSchema->foreignKeys) == false) {
$this->addForeignKey('fk-product-user_id', $this->tableName, 'user_id', User::tableName(), 'id');
}
}

Related

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

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);
}

integrity violation while seeding

This is my seeder class below
<?php
use Illuminate\Database\Seeder;
class RequestTableSeeder extends Seeder
{
public function run()
{
$faker = Faker\Factory::create();
for($i=1;$i<=5;$i++){
DB::table('requests')->insert([
"location_id"=>$faker->numberBetween(1,5),
"level_id"=>$faker->numberBetween(0,1),
"subject_id"=>$faker->numberBetween(0,1),
"first_name"=>$faker->firstName,
"last_name"=>$faker->lastName,
"contact"=>$faker->unique()->phoneNumber,
"email"=>$faker->unique()->email,
"description"=>$faker->text(1000),
]);
}
}
}
Here is my levelseeder class:
<?php
use Illuminate\Database\Seeder;
class SubjectTableSeeder extends Seeder
{
public function run()
{
$faker = Faker\Factory::create();
for($i=1;$i<=5;$i++)
{
DB::table('subjects')->insert([
"name"=>$faker->text(5),
]);
}
}
}
while i try to seed from the command i get:
[PDOException]
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`tutor`.`requests`, CONSTRAINT `requests_level_id_foreign` FOREIGN KEY (`level_id`) REFERENCES `levels` (`id`) ON DELETE CASCADE)
i also checked my subject seeder class.But i could not find the error.This are my seeder class
You are trying to insert a level_id that references a row in the level table that doesn't exist!
In order for this to work your level table needs to be seeded with at least 5 records with the id of 1,2,3,4,5
If you are doing this, maybe the order of your seeders is wrong. Make sure the LevelTableSeeder runs before the RequestTableSeeder.
Further, it seems that subject_id will most likely fail next. This is intended behavior when using foreign keys which are used to ensure database integrity.

Laravel migration can't add foreign key

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.

Can't store a new row - SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

My clients table and users table are child tables of my businesses table. So both the clients and users table contain a business_id column that refers to the id column of the businesses table:
public function up()
{
Schema::create('clients', function(Blueprint $table)
{
$table->increments('id');
$table->integer('business_id')->unsigned();
$table->foreign('business_id')->references('id')->on('businesses');
$table->string('first_name');
$table->string('last_name');
Etc…
I am able to store a new user, it works fine, but I keep getting this error when trying to store a new row into my clients table :
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails
(laravel.clients, CONSTRAINT clients_business_id_foreign FOREIGN
KEY (business_id)
Client.php model
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['business_id', 'first_name', 'last_name'];
/**
* Business where this user works.
*
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function businesses()
{
return $this->belongsTo('App\Business');
}
Business.php model
/**
* Clients that use this business.
*
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function clients()
{
return $this->hasMany('App\Client','business_id');
}
ClientsController.php
public function store(ClientsRequest $request)
{
var_dump(Auth::user()->business_id);
$clientinfo = Request::all();
Client::create($clientinfo);
$client = new Client;
$client->business_id = Auth::user()->business_id;
$client->first_name = $clientinfo['first_name'];
$client->last_name = $clientinfo['last_name'];
//$client->save();
$business->clients()->save($client);
$last_inserted_id = $data->id;
return redirect('clients/'.$last_inserted_id.'/edit');
The only thing I’m not sure is the way I’m retrieving the business_id (from the users table), via Auth. When I var_dump that value, I get :
string(1) "7"
I know the id value is 7 in my businesses table, that’s what I’m looking for, but not sure if it should be converted to integer.
And, not sure if I have to save using :
$client->save();
Or
$business->clients()->save($client);
Thanks
Both following are correct ways, but first one is more Laravel than later,
public function store(ClientsRequest $request)
{
$client = new Client([
'first_name' => $request->get('first_name'),
'last_name' => $request->get('last_name'),
]);
$client = Business::findOrFail(Auth::user()->business_id)
->clients()
->save($client);
return redirect('clients/'.$client->id.'/edit');
}
P.S. above business_id will be automatically added to client by Eloquent
Other way is like you did, where you are inserting a business_id manually.
public function store(ClientsRequest $request)
{
$clientinfo = Request::all();
$client = Client::create([
'business_id' => Auth::user()->business_id;
'first_name' => $clientinfo['first_name'];
'last_name' => $clientinfo['last_name'];
]);
return redirect('clients/'.$client->id.'/edit');
}
You are receiving error because of following statement in your code,
Client::create($clientinfo);
Above statement will attempt to create a database entry without business_id which is a foreign key and should be supplied but wasn't and hence error.
And you don't have to worry about type-conversion between int<->string, PHP is very good at it.
Read More

Laravel 5.1 Migration and Seeding Cannot truncate a table referenced in a foreign key constraint

I'm trying to run the migration (see below) and seed the database, but when I run
php artisan migrate --seed
I get this error:
Migration table created successfully.
Migrated: 2015_06_17_100000_create_users_table
Migrated: 2015_06_17_200000_create_password_resets_table
Migrated: 2015_06_17_300000_create_vehicles_table
[Illuminate\Database\QueryException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
)) (SQL: truncate `users`)
[PDOException]
SQLSTATE[42000]: Syntax error or access violation: 1701 Cannot truncate a table
referenced in a foreign key constraint (`app`.`vehicles`, CONSTRAINT `vehic
les_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `app`.`users` (`id`
))
I looked up what this error is supposed to mean, and also found examples of other people running into the same problem, even just related to using MySQL, and their solutions, but applying:
DB::statement('SET FOREIGN_KEY_CHECKS=0;'); and
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
Within down() doesn't seem to work and when I run describe in MySQL the tables look right.
The migrations are named properly to make sure the users table is migrated first, and then vehicles so the foreign key can be applied, and the tables being setup up correctly suggests the migrations were run, but then the error occurs. I dropped and recreated the DB and tried it again and it is the same result. I also don't understand why it is trying to truncate on the first migration and seed of the database, I wouldn't have thought that would occur when you tried to run php artisan migrate:refresh --seed.
// 2015_06_17_100000_create_users_table.php
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username', 60)->unique();
$table->string('email', 200)->unique();
$table->string('password', 255);
$table->string('role')->default('user');
$table->rememberToken();
$table->timestamps();
});
}
}
public function down()
{
Schema::drop('users');
}
// 2015_06_17_300000_create_vehicles_table.php
class CreateVehiclesTable extends Migration
{
public function up()
{
Schema::create('vehicles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('make');
$table->string('model');
$table->string('year');
$table->string('color');
$table->string('plate');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
}
public function down()
{
Schema::drop('vehicles');
}
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
App\User::truncate();
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
And it works!
As the error says, you can not truncate tables referenced by foreign keys. Delete should work though...
DB::table('some_table')->delete();
before drop
Schema::disableForeignKeyConstraints();
and before close run method
Schema::enableForeignKeyConstraints();
To clear a table using Eloquent:
Model::query()->delete();
Example using default user model
User::query()->delete();
I faced the same issue with my Role and Permission setup and this is what I did that worked as I wanted. Truncate() will reset the Increment column to 1 but throw a foreign key error while delete on the other hand works fine but doesn't reset the increment column, so I did the following in my Seeder's file (i.e RoleSeeder.php in my case)
1. [ delete() method ]
$roles = [];
... // Some foreach statement to prepare an array of data for DB insert()
// Delete and Reset Table
DB::table('roles')->delete();
DB::statement("ALTER TABLE `roles` AUTO_INCREMENT = 1");
// Insert into table
DB::table('roles')->insert($roles);
This will cascade all other child tables attached to the roles table. in my case users_roles table. This way I avoided disabling and enabling foreign key checks.
2. Something to put in mind / Second Approach [ truncate() method ]
if you don't have the intention of deleting all the data stored in the child's table (in my case users_roles table) ... You can go with truncate() and then in the DatabaseSeeders.php file you disable and enable foreign key check. As I tested this and the users_roles data was intact, the seed on affected roles table.
//RoleSeeders.php File
$roles = [];
... // Some foreach statement to prepare an array of data for DB insert()
// Truncate Table
DB::table('roles')->truncate();
// Insert into table
DB::table('roles')->insert($roles);
Then in the DatabaseSeeder.php file, you do;
public function run()
{
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$this->call([
RoleSeeder::class,
]);
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
But I prefer the delete() method, since I don't have to disable/enable the foreign key check
you can use
DB::table('your_table_name')->delete();
to empty a table, this won't delete the table structure. But the auto increment id will not start from initial number.
Here is what works for me every time.
When you're adding the foreign key, make sure to add cascade.
the syntax is like this
$table->foreign('column')->references('id')->on('table_name')->onDelete('cascade');
Make sure to replace id with whatever field is applicable for you.
Now before running the seeding add this instead of trucate
DB::statement('DELETE FROM table_name');
It will delete all the data.
Hope this helps.
You could just drop it with.
$table->dropForeign('posts_user_id_foreign');
I'm using Laravel 7.x, this worked for me. Goes without saying that it should only be used in development. To read more, check it out here.
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
// the Eloquent part and disabling and enabling of foreign keys is only intended for development
Eloquent::unguard();
//disable foreign key check for this connection before running seeders
DB::statement('SET FOREIGN_KEY_CHECKS=0;');
$this->call(RolesTableSeeder::class);
$this->call(UsersTableSeeder::class);
// supposed to only apply to a single connection and reset it's self
// but I like to explicitly undo what I've done for clarity
DB::statement('SET FOREIGN_KEY_CHECKS=1;');
}
}