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');
});
}
Related
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');
I have a table foo and a migration for it like this (just showing the up method):
public function up()
{
Schema::table('foo', function (Blueprint $table) {
$table->unsignedBigInteger('boo_id');
});
Schema::table('foo', function (Blueprint $table) {
$table->foreign('boo_id')->references('id')->on('boos');
});
}
So I have a boo_id foreign key on boos.id. Now I would like to create a migration that will alter the field boo_id to be text and not be foreign key anymore. How can I do that?
You first need to delete the foreign key and the index created for the foreign and then change the data type of the column. A migration like this would help:
public function up()
{
Schema::table('foo', function (Blueprint $table) {
$table->dropForeign('foo_boo_id_foreign');
$table->dropIndex('foo_boo_id_foreign');
});
Schema::table('foo', function (Blueprint $table) {
$table->text('boo_id')->change();
});
}
Please note that they must be in two seperate Schema::table bodies, otherwise you will face an error: Syntax error or access violation: 1170 BLOB/TEXT column 'boo_id' used in key specification without a key length (SQL: ALTER TABLE foo CHANGE boo_id boo_id TEXT DEFAULT NULL). Also note that the names passed to dropForeign and dropIndex functions might be different for you, you should check that in your DB to be sure, as that naming convention is not mandatory.
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 2 tables, one has different columns to record different users names based on authorisation level. but i would like to link to two together. at the moment i have tried the following:
User.php
public function approvals()
{
return $this->hasMany(Approval::class);
}
Approval.php
public function qs() {
return $this->belongsTo(User::class, 'id', 'qs');
}
index.blade.php
<td>{{ $approval->qs->name }}</td>
approvals db structure
Schema::create('approvals', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('project_id');
$table->integer('stage');
$table->unsignedBigInteger('qs')->nullable();
$table->unsignedBigInteger('pm')->nullable();
$table->unsignedBigInteger('rcm')->nullable();
$table->unsignedBigInteger('doc')->nullable();
$table->unsignedBigInteger('vpoc')->nullable();
$table->unsignedBigInteger('vpof')->nullable();
$table->timestamps();
});
users db structure
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email', 100)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
Am i going about this all wrong, the qs table column needs to be linking to the users.id?
It seems qs is the user id of the User model. So the relation to the Approval model is
public function qs()
{
return $this->belongsTo(User::class, 'qs');
}
And in User model
public function approvals()
{
return $this->hasMany(Approval::class, 'qs');
}
Now you can use
{{ $approval->qs->name }}
Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with a _ followed by the name of the primary key column. However, if the foreign key on the Model is not parent_id, you may pass a custom key name as the second argument to the belongsTo method.
Laravel Documentation
If a parent model does not use id as its primary key, or you want to join the child model to a different column, you may pass a third argument to the belongsTo method:
public function qs() {
return $this->belongsTo(User::class, 'foreign_key_here_from_child_table', 'custom_column_from_parent_table');
}
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');
}
}