Im trying to do a many to many relationship, where many brand has many product types and also has many models. And many product types has many brands:
So this are my eloquent relationships:
Ptype.php:
class Ptype extends Model
{
public function marca(){
return $this->belongsTo(Brand::class, 'brand_id', 'id');
}
}
Brand.php:
public function ptype(){
return $this->hasMany(Ptype::class, 'ptype_id', 'id');
}
Migrations:
brands_table:
public function up()
{
Schema::create('models', function (Blueprint $table) {
$table->id();
$table->string('modelName');
$table->unsignedBigInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands');
$table->timestamps();
});
}
ptypes:
public function up()
{
Schema::create('ptypes', function (Blueprint $table) {
$table->id();
$table->string('productType');
$table->unsignedBigInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands');
$table->integer('created_by')->nullable();
$table->integer('updated_by')->nullable();
$table->timestamps();
});
}
What am i doing wrong?
This is the exact error:
SQLSTATE[HY000]: General error: 1005 Can't create table `axis`.`ptypes` (errno
: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table `ptypes`
add constraint `ptypes_brand_id_foreign` foreign key (`brand_id`) references `b
rands` (`id`))
Firstly, check your migration files orders. As far as I see, they should be like this:
brands migration
models migration
ptypes migration
Also, you can use foreignId instead of foreign, references, etc.
$table->foreignId('brand_id')->constrained(‘brands’);
So, you can delete these;
$table->unsignedBigInteger('brand_id');
$table->foreign('brand_id')->references('id')->on('brands');
Related
Hey guys I tried too much stuff and read some blogs or discussion I didn't fix my problem I'm new in laravel this project. I got error when I want to create to database this error like
PDOException::("SQLSTATE[HY000]: General error: 1005 Can't create table `portal`.`employees` (errno: 150 "Foreign key constraint is incorrectly formed")")
my migration for payments:
public function up()
{
Schema::create('payments', function (Blueprint $table) {
$table->bigInteger('id');
$table->unsignedBigInteger('employee_id');
$table->decimal('salary',16);
$table->decimal('amount_paid',16);
$table->unsignedBigInteger('paid_by');
$table->string('remark');
$table->string('department',50);
$table->timestamps();
});
Schema::table('payments', function($table) {
$table->foreign('employee_id')->references('id')->on('employees')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('paid_by')->references('id')->on('users');
});
}
my migration for employees:
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->unsignedBigInteger('id');
$table->string('name');
$table->string('department');
$table->string('location');
$table->string('telephone');
$table->decimal('salary',16);
$table->string('cover_image');
$table->foreign('department')->references('name')->on('departments')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
Department Table:
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->bigInteger('id');
$table->string('name');
$table->timestamps();
});
}
my migration folder:
https://i.stack.imgur.com/pCsbg.png
making foreign keys on non unique columns is not a good idea, and only innodb for mysql support that, see mysql doc.
instead of:
$table->foreign('department')->references('name')->on('departments')->onUpdate('cascade')->onDelete('cascade');
you should make the foreign key regularly like:
$table->bigInteger('department_id');
$table->foreign('department_id')->references('id')->on('departments')->onUpdate('cascade')->onDelete('cascade');
You can simply set the foreign key on the department Id and of course, it's much better and has better performance setting a foreign key on unique keys.
Here's the relevant models.
App\CourseItem => https://pastebin.com/PbYJAan1
App\CourseItemEvent => https://pastebin.com/RV6FBiac
If you look at App\CourseItem
I must define the foreign key
public function courseitemevent()
{
return $this->hasOne(CourseItemEvent::class, 'courseitem_id');
}
It is ignoring all the tablenames i am defining
Even thought ^ works fine i thought it would be cool to find out why
Please check out this migration structure.this is how you make a foreign key.
//this is just an example for foreign key.user_id of the user_permission table is referencing the user table id.
public function up()
{
Schema::create('user_permissions', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->index();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
I've been trying to create a laravel model class that has a foreign key, but it gives an error: Foreign key constraint is incorrectly formed.
I know that this question have been asked multiple times, but the answers on these questions doesn't solve my problem.
My Table migration:
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('Tables', function (Blueprint $table) {
$table->id('id')->unique();
$table->integer('tablenumber');
$table->unsignedBigInteger('ReservationId');
$table->foreign('ReservationId')->references('id')->on('reservations')->onDelete('cascade');
});
}
My Reservations Migration:
public function up()
{
Schema::enableForeignKeyConstraints();
Schema::create('Reservations', function (Blueprint $table) {
$table->id('id')->unique;
$table->datetime('ReservationOn');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
I'm trying to create a foreign key with ReservationId in the Orders migration, using the id from the Reservations Migration.
I guess it will be a stupid mistake somewhere, but I don't see where. (I'm still learning for it ;) )
Thanks for helping me out.
I have created a table called 'users'.There are tables called 'companies','designations','departments'.I want to add company_id,designation_id,department_id columns to users table as foreign keys.
I tried this but it didn't work
public function up()
{
Schema::table('users', function (Blueprint $table) {
$table->integer('department_id');
$table->integer('company_id');
$table->integer('designation_id');
$table->foreign('department_id')->references('id')->on('departments')->onDelete('restrict')->onUpdate('restrict');
$table->foreign('company_id')->references('id')->on('companies')->onDelete('restrict')->onUpdate('restrict');
$table->foreign('designation_id')->references('id')->on('designations')->onDelete('restrict')->onUpdate('restrict');
});
}
public function down()
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn(['department_id','company_id','designation_id']);
});
}
When I migrate the migration it shows this error.
Illuminate\Database\QueryException : SQLSTATE[HY000]: General
error: 1005 Can't create table lanwadb.users (errno: 150 "Foreign
key constraint is incorrectly formed") (SQL: alter table users add
constraint users_department_id_foreign foreign key (department_id)
references departments (id) on delete restrict on update restrict)
Designation migration as follows,
public function up()
{
Schema::create('designations', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestampsTz();
});
}
Department migration as follows,
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('company_id');
$table->timestampsTz();
});
}
```
To make relationship the foreign key field should be indexed. Here you have three columns you want to use as foreign key 'company_id', 'department_id' and 'designation_id'. In Laravel migration you can use unsigned() function to index them.
Example:
$table->integer('department_id')->unsigned();
$table->integer('company_id')->unsigned();
$table->integer('designation_id')->unsigned();
There is another function called unsignedInteger() by which you can make a column both Integer and Unsigned.
$table->unsignedInteger('department_id');
$table->unsignedInteger('company_id');
$table->unsignedInteger('designation_id');
use this:
$table->integer('department_id')->unsigned()->nullable();
$table->integer('company_id')->unsigned()->nullable();
$table->integer('designation_id')->unsigned()->nullable();
$table->foreign('department_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('company_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');
$table->foreign('designation_id')->references('id')->on('departments')->onDelete('cascade')->onUpdate('cascade');
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');
}
}