Foreign Key in Laravel 5.1 - NO Relationship - mysql

Need Help guys! Whats wrong with my migrations, It's not creating a relationship between users table and posts table. Here's what I did:
migrate users table
create posts table
migrate posts table with foreign key
Users Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
Posts Migration:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title', 255);
$table->text('content');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
Nothing Happen with my database. Take a look at my database:
Compared with this:
.. I'm using Laravel 5.1

You need to add it in two step. Schema::create() is only used to create table.
To add relation you need to write it within Schema::table().
Try following :
In CreatePostsTable :
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('title', 255);
$table->text('content');
$table->timestamps();
});
Schema::table('posts', function($table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}

Related

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row error

Im currently reffering a ecommerce lesson using laravel 8.when creating categories for the products im keep getting this error message while migrating.
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (SQL: drop table if exists products)
This is my create_products_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->string('name');
$table->string('slug');
$table->text('description');
$table->integer('price');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
and here is create_category_product_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCategoryProductTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('category_product', function (Blueprint $table) {
$table->increments('id');
$table->integer('product_id')->unsigned()->nullable();
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
$table->integer('category_id')->unsigned()->nullable();
$table->foreign('category_id')->references('id')->on('category')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('category_product');
}
}
Much appreciate if someone can teach me to solve this. Thank You!

Laravel/SQL error when adding foreign keys

I am trying to make some relationships between some tables but have an error that states..
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 ')' at line 1 (SQL: alter table users add
constraint users_board_id_foreign foreign key (board_id)
references `` ())
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->foreign('board_id')->unsigned();
$table->foreign('board_id')->references('id')->on('boards');
$table->foreign('message_id')->references('id')->on('messages');
$table->foreign('message_id')->unsigned();
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
This table is supposed to be related to this table...
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBoardsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('boards', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 100)->unique();
$table->foreign('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('link_id')->unsigned();
$table->foreign('link_id')->references('id')->on('links');
$table->foreign('message_id')->unsigned();
$table->foreign('message_id')->references('id')->on('messages');
$table->foreign('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('boards');
}
}
I've already drop the table and the schema and started fresh and still get the same error! Please be kind :!
Try this one:
// USERS
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('board_id')->unsigned();
$table->foreign('board_id')->references('id')->on('boards');
$table->integer('message_id')->unsigned();
$table->foreign('message_id')->references('id')->on('messages');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
//BOARDS
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBoardsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('boards', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 100)->unique();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->integer('link_id')->unsigned();
$table->foreign('link_id')->references('id')->on('links');
$table->integer('message_id')->unsigned();
$table->foreign('message_id')->references('id')->on('messages');
$table->integer('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('boards');
}
}
You can't define columns with foreign():
$table->integer('board_id')->unsigned();
$table->foreign('board_id')->references('id')->on('boards');
$table->integer('message_id')->unsigned();
$table->foreign('message_id')->references('id')->on('messages');
The same goes for the boards migration.
I experienced very alike situation, my schema
`
public function up() {
Schema::dropIfExists('countries_states');
Schema::create('countries_states', function (Blueprint $table) {
$table->id();
$table->foreignId('country_id')->unsigned();
$table->foreign('country_id')->references('id')->on('countries');
$table->string('state', 30);
$table->string('abbr', 30);
});
//Schema::enableForeignKeyConstraints();
}
`
And I had the same
I solved it by granting access to specific user for specific database and voila - everything started to function like charm

Cannot add foreign key constraint [Laravel 5.6]

tl;dr. Solution:
Thanks to Jonas.
the problem was that the tables I was referring as foreign, were not InnoDB.
I added raw SQL statements in alter migrations and then added the foreign keys:
DB::statement("ALTER TABLE table ENGINE='InnoDB';");
Original question
First, before the Stackoverflow police bust me, I know this question is probably 83% of the database of this website. But me is special (Kidding, I know I'm not). But I've tried most of the common stuff and nothing seems to work. So probably I'm overseeing something.
Error
General error: 1215 Cannot add foreign key constraint (SQL: alter table applications add constraint applications_user_id_foreign foreign key (user_id) references users (id) on delete cascade)
This is my migration:
public function up()
{
Schema::create("applications", function(Blueprint $table) {
$table->engine = "InnoDB";
$table->increments('id');
$table->timestamps();
});
Schema::table('applications', function($table) {
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('job_request_id')->unsigned()->index();
$table->foreign('job_request_id')->references('id')->on('job_requests')->onDelete('cascade');
$table->integer('status')->default(0);
});
}
What I've already tried:
1.
public function up()
{
Schema::create("applications", function(Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('job_request_id')->unsigned();
$table->foreign('job_request_id')->references('id')->on('job_requests')->onDelete('cascade');
$table->integer('status')->default(0);
});
}
2.
public function up()
{
Schema::create("applications", function(Blueprint $table) {
$table->engine = "InnoDB";
$table->increments('id');
$table->timestamps();
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->integer('job_request_id')->unsigned();
$table->foreign('job_request_id')->references('id')->on('job_requests')->onDelete('cascade');
$table->integer('status')->default(0);
});
}
Splitting the migration into two files (A create and an alter). Even adding each reference one by one.
4.- using DB::statement('SET FOREIGN_KEY_CHECKS=0;'); and =1 at the beginning an the end og the migration.
5.- removing the unsigned() and the index().
Might mean something:
1.- When I rollback the migration, it doesn't delete the table. So if I rollback and migrate, would give me a "already exists error".
2.- I already have migrations which reference the same items, i.e:
Schema::create('job_requests', function (Blueprint $table) {
...
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
...
});
UPDATE
For the drop methods I've tried:
For the create migrations
public function down()
{
Schema::drop('applications');
}
public function down()
{
Schema::dropIfExists('applications');
}
2.- For the alter migrations
public function down()
{
Schema::table('applications', function (Blueprint $table) {
$table->dropForeign(['user_id']);
$table->dropColumn('user_id');
$table->dropForeign(['job_request_id']);
$table->dropColumn('job_request_id');
});
}
UPDATE 2:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('first_name');
$table->string('last_name')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
public function up()
{
Schema::create('job_requests', function (Blueprint $table) {
$table->increments('id');
$table->integer('status')->default(0);
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('job_requests');
}
I added three more alter migration:
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->engine = "InnoDB";
});
}
///////////////////////////
public function up()
{
Schema::table('job_requests', function (Blueprint $table) {
$table->engine = "InnoDB";
});
}
///////////////////////////
public function up()
{
Schema::table('applications', function (Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('job_request_id')->references('id')->on('job_requests')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('applications', function (Blueprint $table) {
$table->dropForeign(['user_id']);
$table->dropForeign(['job_request_id']);
});
}
Without luck yet.
The referenced tables also have to use the InnoDB engine.
You can change them with raw SQL statements:
DB::statement("ALTER TABLE users ENGINE='InnoDB';");
DB::statement("ALTER TABLE job_requests ENGINE='InnoDB';");
for deleting the table:
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('applications');
}

How to get nested array from `sql/mysql` under a common column using `groupby` without using foreach to structure the data?

Lets say the table tracker contains this columns(id,section,user_id,message) and other one is user table which contains user data and user_id is the foreign key in the table tracker so I am using join to get the name from user table and I am using laravel.
The response is like this:-
{'id'=1,'name'='pavan','section'='marketing','message'='something'}
The required structure is a nested array under user_id like this:-
{
//user_id 1:
[name,section,message],
2:
[name,section,message]
}
How do I get this using MySQL query?
//user model
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
//tracker model
public function up()
{
Schema::create('trackers', function (Blueprint $table) {
$table->increments('id');
$table->enum('section',['Marketing','Sales','Customer','Trainer','Operations']);
$table->string('subject')->nullable();
$table->longText('content');
$table->enum('status',['processing','resolved']);
$table->date('date');
$table->unsignedInteger('user_id');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users');
});
}
//get data method in tracker model
public function getdata(){
return \DB::table('trackers')
->join('users','users.id','=','trackers.user_id')
->select('trackers.user_id','users.name',
'trackers.created_at','trackers.id','date',
'trackers.status','trackers.section','trackers.content')
->orderBy('created_at','DESC')->get();
}
//query
$dat=new Tracker;
$data=$dat->getdata()->where('date',Carbon::today()->
toDateString())->where('status','processing');
$dat=new Tracker;
$data=$dat->getdata()->where('date',Carbon::today()->
toDateString())->where('status','processing')->get();
get() will return the collection after getting the collection you can use
You can data like this with
$dat->groupBy('user_id');
This will return the data as you expected.
You can get more information about collection->groupby()
https://laravel.com/docs/5.6/collections#method-groupby

Error: Foreign key Constraint Violation. can't add/update a child row

Can anyone help me ?? i am stuck in setting foreign key Constraint.
I am getting
ERROR:foreign key constraint violation: Can't add/update a child row.
I am having a users,Projects,hours,tasks and sub-tasks table.
I have created migrations for tables in this order
1.Users 2.Projects 3.Hours 4.Tasks 5.Sub-tasks
After these migrations, I created a new migration in which I added five new fields into hours table 3 fields for hours and two foreign keys from tasks and sub-tasks table i-e task_id and subtask_id.
i have already made foreign keys unsigned(), and these foreign keys are the same as in parent tables.
i have searched alot but most of replies says that you are creating child table before parent table or something like this.
Hours Migration
class CreateHoursTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('hours', function (Blueprint $table) {
$table->increments('id');
$table->string('actual_hours');
$table->string('productive_hours');
$table->integer('project_id')->unsigned();
$table->foreign('project_id')
->references('id')
->on('projects')
->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('hours');
}
}
Tasks migration:
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
/* Relations Table Field Starts */
$table->integer('project_id')->unsigned();
$table->foreign('project_id')
->references('id')
->on('projects')
->onDelete('cascade');
/* Relations Table Field Ends */
$table->string('name');
$table->string('key');
$table->text('description');
$table->integer('percentDone');
$table->date('duedate');
$table->integer('reporter');
$table->integer('follower');
$table->string('tags');
/*Task ENUM Fields Starts*/
$table->enum('types', ['New Feature','Bug','Improvement','Task']);
$table->enum('priority', ['Blocker','Minor','Major','Trivial','Critical']);
$table->enum('workflow', ['Todo','In Progress','In QA','Completed']);
$table->enum('component', ['Web','Android','IOS']);
/*Task ENUM Fields Starts*/
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('tasks');
}
}
Sub-tasks Migration:
class CreateSubtasksTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('subtasks', function (Blueprint $table) {
$table->increments('id');
/* Relations Table Field */
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->integer('task_id')->unsigned();
$table->foreign('task_id')
->references('id')
->on('tasks')
->onDelete('cascade');
$table->string('name');
$table->text('description');
$table->integer('percentDone');
$table->date('duedate');
$table->string('reporter');
$table->string('follower');
$table->string('tags');
$table->enum('priority', ['Blocker','Minor','Major','Trivial','Critical']);
$table->enum('Workflow', ['Todo','In Progress','In QA','Completed']);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('subtasks');
}
}
Migration To Add New Fields in Hours Table:
class AlterTableHoursAddColumnsHours extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('hours', function (Blueprint $table) {
$table->integer('estimated_hours');
$table->integer('internal_hours');
$table->integer('consumed_hours');
/*Now Fields for Task And Subtask Tables Starts*/
$table->integer('task_id')->unsigned();
$table->foreign('task_id')
->references('id')
->on('tasks')
->onDelete('cascade');
$table->integer('subtask_id')->unsigned();
$table->foreign('subtask_id')
->references('id')
->on('subtasks')
->onDelete('cascade');
/*Now Fields for Task And Subtask Tables Ends*/
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('hours', function (Blueprint $table) {
$table->dropColumn('estimated_hours');
$table->dropColumn('internal_hours');
$table->dropColumn('consumed_hours');
$table->dropForeign('hours_task_id_foreign');
$table->dropColumn('task_id');
$table->dropForeign('hours_subtask_id_foreign');
$table->dropColumn('subtask_id');
});
}
}
Is this because i created hours table before Tasks and Sub-tasks table. ??? Any Solution ?? Any Help ??