laravel migration use auto increment when its not primary - laravel

I'm trying to create a table with Laravel migrations but I'm having some trouble. I just need to create a table with a primary pair ('user_id' and 'media_id'), being 'inc' an auto increment. I can do it in MySQL, but I can't manage to do it with Laravel Migrations since increments() also set the field as primary. error i get
SQLSTATE[42000]: Syntax error or access violation: 1075 Incorrect table definition; there can be only one auto column and it must be defined as a key
thats i hae done so far
public function up()
{
Schema::create('tagtables', function (Blueprint $table) {
$table->integer('media_id');
$table->integer('user_id');
$table->boolean('approved')->default(false);
$table->increments('inc')->unsigned();
$table->timestamps();
$table->dropPrimary('tagtables_inc_primary');
$table->primary(array('user_id','media_id'));
// $table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
// $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
// Schema::table('tagtables', function (Blueprint $table) {
// //$table->increments('id');
// $table->primary(array('user_id','media_id'));
// $table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
// $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
// });
}

I think you need this:
public function up()
{
Schema::create('tagtables', function (Blueprint $table) {
$table->increments('inc');
$table->integer('media_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->boolean('approved')->default(false);
$table->timestamps();
$table->index(['user_id', 'media_id']);
$table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
}
and put this in the model:
protected $primaryKey = 'inc';

I found solution to problem which is ti define that column inc (which auto increments) after creating schema.
That how it should be
public function up()
{
Schema::create('tagtables', function (Blueprint $table) {
$table->integer('media_id');
$table->integer('user_id');
$table->boolean('approved')->default(false);
// $table->increments('inc');
$table->timestamps();
// $table->dropPrimary( 'tagtables_inc_primary' );
$table->primary(array('user_id','media_id'));
// $table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
// $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
});
DB::statement('ALTER Table tagtables add id INTEGER NOT NULL UNIQUE AUTO_INCREMENT;');
// Schema::table('tagtables', function (Blueprint $table) {
// //$table->increments('id');
// $table->primary(array('user_id','media_id'));
// $table->foreign('media_id')->references('id')->on('media')->onUpdate('cascade')->onDelete('cascade');
// $table->foreign('user_id')->references('id')->on('users')->onUpdate('cascade')->onDelete('cascade');
// });
}
chema

Related

Laravel - How to add foreign key reference to already existing migration

In my Larave-8, I created a table using this migration:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id');
$table->string('first_name',50);
$table->string('last_name',50);
$table->string('other_name',50)->nullable();
$table->string('gender',20);
$table->string('user_photo',350)->nullable();
$table->integer('nationality_id');
$table->string('marital_status',50);
$table->date('dob')->nullable();
$table->string('address', 300)->nullable();
$table->integer('country_id')->nullable();
$table->integer('state_id')->nullable();
$table->integer('city_id')->nullable();
$table->string('cv_file',350)->nullable();
$table->text('summary')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
How do I alter the table through migration and add these:
$table->foreign('nationality_id')->references('id')->on('countries');
$table->foreign('country_id')->references('id')->on('countries');
$table->foreign('state_id')->references('id')->on('state_origins');
$table->foreign('city_id')->references('id')->on('cities');
Thanks
create another migration like to alter existing table
public function up()
{
Schema::table('profiles', function (Blueprint $table) {
$table->foreign('nationality_id')->references('id')->on('countries');
$table->foreign('country_id')->references('id')->on('countries');
$table->foreign('state_id')->references('id')->on('state_origins');
$table->foreign('city_id')->references('id')->on('cities');
});
}
public function down() {
Schema::table('profiles', function (Blueprint $table) {
$table->dropForeign('nationality_id');
$table->dropForeign('country_id');
$table->dropForeign('state_id');
$table->dropForeign('city_id');
});
}

primary key is not added as reference to foreign key in laravel 6

I want to add a foreign key to my schools table but the primary key of the provinces table is not added to the foreign key reference.
This is my Schools Table
public function up()
{
Schema::create('schools', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("name");
$table->unsignedTinyInteger("province_id");
});
}
and Provinces Table
public function up()
{
Schema::create('provinces', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("name",255);
});
}
and this is my Foreign key constraint
public function up()
{
Schema::table('schools', function (Blueprint $table) {
$table->foreign('province_id')->reference('id')->on('provinces');
});
}
and this is the error
enter image description here
If there is a solution tell me.
Thanks.
Try this and also check the sequence of your migrations.
public function up()
{
Schema::create('student_profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string("name",64);
$table->string("father_name",64);
$table->string("last_name",64);
$table->string("grand_father_name",64);
$table->string("graduation_year",4)->unique();
$table->enum("gender",['0','1']);
$table->unsignedSmallInteger('school_id')->nullable();
$table->unsignedTinyInteger("province_id")->nullable();
$table->foreign('school_id')->reference('id')->on('schools')-
>onDelete('set null');
$table->foreign('province_id')->reference('id')->on('provinces')->onDelete('set null');
});
}
public function up()
{
Schema::table('schools', function (Blueprint $table) {
$table->unsignedBigInteger('province_id')->nullable();
$table->foreign('province_id')->reference('id')->on('provinces')
->onDelete('set null');
});
}

General error: 3730 Cannot drop table 'questionnaires' referenced by a foreign key constraint (SQL: drop table if exists `questionnaires`) Laravel

I have a problem when I rollback my boards. It is as follows:
SQLSTATE[HY000]: General error: 3730 Cannot drop table 'questionnaires' referenced by a foreign key constraint 'questions_questionnaire_id_foreign' on table 'questions'. (SQL: drop table if exists `questionnaires`)
For this I have 2 tables involved, which is Questionnaire and Question.
Question
lass CreateQuestionsTable extends Migration{
public function up(){
Schema::create('questions', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('questionnaire_id');
$table->text('description');
$table->text('iframe');
$table->text('image')->nullable();
$table->timestamps();
});
}
public function down(){
Schema::table('questions', function (Blueprint $table) {
$table->dropColumn('questionnaire_id');
$table->dropForeign('questions_questionnaire_id_foreign');
});
Schema::dropIfExists('questions');
}
}
Questionnaire
class CreateQuestionnairesTable extends Migration{
public function up(){
Schema::create('questionnaires', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->string('description');
$table->timestamps();
});
}
public function down(){
Schema::dropIfExists('questionnaires');
}
}
And then add the questionnaire FK to the question table. Alter table
class AddToQuestionnaireIdToQuestionsTable extends Migration{
public function up(){
Schema::table('questions', function (Blueprint $table) {
$table->foreign('questionnaire_id')->references('id')->on('questionnaires')
->onDelete('cascade')
->onUpdate('cascade');
});
}
public function down(){
Schema::dropIfExists('questions');
}
}
However when I rollback I get the aforementioned error. What am I doing wrong?
You are dropping the question table in the wrong place. You should rollback only what you did roll forward.
Question: if you created a table, here you drop the table.
Class CreateQuestionsTable extends Migration
{
public function up()
{
Schema::create('questions', function (Blueprint $table)
{
$table->id();
$table->unsignedBigInteger('questionnaire_id');
$table->text('description');
$table->text('iframe');
$table->text('image')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('questions');
}
}
ForeigKey: if you created a column and/or foreign key, drop then here.
class AddToQuestionnaireIdToQuestionsTable extends Migration
{
public function up()
{
Schema::table('questions', function (Blueprint $table)
{
$table->foreign('questionnaire_id')
->references('id')
->on('questionnaires')
->onDelete('cascade')
->onUpdate('cascade');
});
}
public function down()
{
Schema::table('questions', function (Blueprint $table)
{
$table->dropForeign('questions_questionnaire_id_foreign');
$table->dropColumn('questionnaire_id');
});
}
}
If you want to delete a table and get a foreign key error, do as the code below in SQL😂
set foreign_key_checks=0;
drop table `yourSchema`.`yourTable`;

How To Delete Multiple Data From Different Table

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

Laravel Integrity constraint violation on db migration

SQLSTATE[23000]: Integrity constraint violation: 1217 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table `users`)
I know this has been answered several times, but still i cant figure our whats wrong with my migration.
First i call the partner migration
public function up()
{
Schema::create('partners', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('admin_id')->unsigned();
$table->string('company_name', 50);
...
}
public function down()
{
Schema::drop('partners');
}
Then i call the Users migration
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('partner_id')->unsigned();
$table->string('email', 70)->unique();
$table->string('first_name', 50);
$table->string('last_name', 50);
$table->string('password', 60);
$table->string('image', 200)->nullable();
$table->string('gender', 10)->nullable();
$table->string('phone', 25)->nullable();
$table->string('nationality', 50)->nullable();
$table->string('address', 200)->nullable();
$table->boolean('is_active')->default(0);
$table->string('single_signon', 30)->nullable();
// Checks if mysql or mariadb supports json data type
if ((DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') && version_compare(DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '5.7.8', 'ge')) {
$table->json('settings')->nullable();
} else {
$table->text('settings')->nullable();
}
$table->softDeletes();
$table->rememberToken();
$table->timestamps();
$table->foreign('partner_id')->references('id')->on('partners')->onDelete('cascade');
});
}
public function down()
{
Schema::table('users', function(Blueprint $table) {
$table->dropForeign('users_partner_id_foreign');
});
Schema::drop('users');
}
Last i call the notification migration:
public function up()
{
Schema::create('notifications', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('notification_type', 10);
// Checks if mysql or mariadb supports json data type
if ((DB::connection()->getPdo()->getAttribute(PDO::ATTR_DRIVER_NAME) == 'mysql') && version_compare(DB::connection()->getPdo()->getAttribute(PDO::ATTR_SERVER_VERSION), '5.7.8', 'ge')) {
$table->json('notification')->nullable();
} else {
$table->text('notification')->nullable();
}
$table->boolean('seen');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
public function down()
{
Schema::table('notifications', function(Blueprint $table) {
$table->dropForeign('notifications_user_id_foreign');
});
Schema::drop('notifications');
}
Can anybody figure out whats wrong with this? i am using laravel 5.3 and php7
The issue is in migration order. It's better to include the migrations in one file and drop the child before the parent, like this:
public function down(){
Schema::drop('notifications');
Schema::drop('users');
Schema::drop('partners');
}
That's because Laravel tries to drop users table before notifications table, which include user_id column that has reference in users table.
public function down()
{
DB::statement('SET FOREIGN_KEY_CHECKS = 0');
Schema::drop('tableName');
DB::statement('SET FOREIGN_KEY_CHECKS = 1');
}
disable foreign key check while droping the table

Resources