Laravel relationships in migrations?

62,951

Solution 1

As far as I know, no relationship table will be created. What you will need to do is have a role_id on your users table, so that when you create a user, the ID of the role will be stored there. This will enable you do select all users where role_id == '1' or whatever it may be. For example:

$admins = User::where('role_id', '=', 1);

Where on the ROLES table the record with ID='1' is admin. So again to answer your question, no relationship table is created, instead the relationship exists within your two tables in the form of a role_id column for each user. Out of interest, are you using foreign keys?

If you want to have a relationships table you could create one called user_roles or something and store the role_id and user_id in there, however I think its easier to use the above method as then you can use all the Laravel/Eloquent goodness.

Hope this helps :)

Solution 2

When creating a migration you can specify foreign keys on your tables, i.e.

public function up()
{
    Schema::table('roles', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        //rest of fields then...
        $table->foreign('user_id')->references('id')->on('users');
    });
}

This will create a foreign key on the user_id column on the roles table. The benefits of foreign keys is that when an update or delete is made the foreign key table will be automatically updated or "cascaded" great description found here

As described on the Laravel documentation you could also specify your cascading on update using the following syntax

$table->foreign('user_id')
  ->references('id')->on('users')
  ->onDelete('cascade');

I would do a bad job of trying to explain it better than the documentation does so please have a read through the "Relationships" section of the Eloquent ORM documentation to see how its done.

Solution 3

It looks like a few of the initial questions were never answered, i.e. "When, and how is the relationship table created" & "will the middle table be created automatically":

As far as I am aware, these tables need to be created manually. So create the migration file like so:

Laravel 5

php artisan make:migration create_role_user_table

Laravel 4

php artisan migrate:make create_role_user_table

Note that the names are singular, and are presented in alphabetical order.

Then in the migration something like:

public function up()
{
    Schema::create('role_user', function($table) {
        $table->increments('id');
        $table->integer('role_id');
        $table->integer('user_id');
        $table->timestamps();
    });
}

Hope that helps. I'm not sure if the timestamps are needed in Pivot Tables or not, so please experiment.

Solution 4

Though its an old Post, I though I can contribute something updated. For Laravel5, Jeffrey Way has developed a package Laravel5 Generators-extended which enhance the generator capability of php artisan for

  • make:migration:schema
  • make:migration:pivot
  • make:seed

For many-to-many relation between users and role, you can just use

php artisan make:migration:pivot users role

and it will generate the required migration class. You don't need to code manually for this.

Solution 5

This video helped me.

https://laracasts.com/series/laravel-5-fundamentals/episodes/14

What was surprising for me was that only one side of the relationship needs pointer_id in migration table, not both. For example, if we have Author with many Articles, we only add

$table->integer('author_id')

to article migration and thats it.

Share:
62,951
qwerty
Author by

qwerty

Updated on August 22, 2020

Comments

  • qwerty
    qwerty over 3 years

    I know you can define table relationships fairly easy with $this->belongs_to(), $this->has_many() etc, but what i don't understand is how the relationship table is created; the table that binds the two tables together (i forgot what the term is called).

    Let's say i'm creating a users table. I want that user to belong to a certain "Role". There are multiple roles, and every role can have multiple users. I will need to also create a roles table for that. So far, so good.

    But after reading the documentation, it says i should add the $this->belongs_to() in the model, not the migration itself. When, and how is the relationship table created? If i create the roles and users tables, and add $this->belongs_to('roles') to the users model, and $this->has_many('users') to the roles model, will the middle table be created automatically?

  • qwerty
    qwerty over 11 years
    Thank you for answering! I figured out that no relationship table is needed if i only store one role per user. But what if every user could have unlimited roles? Then i have no other choice than to store it in another table, right? How would that work? I know Laravel can create and manage these tables automatically for you, but i don't how how, where or when it does it.
  • udgeet patel
    udgeet patel about 9 years
    So which is better, whether to create relations on database itself by changing migration files or just defining relationships in model files? or using both techniques
  • Jeff Puckett
    Jeff Puckett over 7 years
    migrate:make is not in artisan for Laravel 5.4, it's php artisan make:migration
  • abbood
    abbood over 6 years
    @Roark you probably should have mentioned that the column "user_id" should be created first.. otherwise you'll get an error like: ``` [Illuminate\Database\QueryException] SQLSTATE[42703]: Undefined column: 7 ERROR: column "lang_id" referenced in foreign key constraint does not exist (SQL: alter table "op_cities" add constraint "op_cities_lang_i d_foreign" foreign key ("lang_id") references "translator_languages" ("id")) ```
  • abbood
    abbood over 6 years
    example of that here: easylaravelbook.com/blog/…
  • Roark
    Roark over 6 years
    @abbood Updated answer to show more detailed migration example
  • James
    James almost 5 years
    Why does it always happened to me that only $table->unsignedBigInteger('user_id'); works?
  • Roark
    Roark almost 5 years
    @james check this article out. If you’re on Laravel 5.8 it could be the reason: laraveldaily.com/…
  • Alireza Bijantabar
    Alireza Bijantabar about 2 years
    where are the relations?
  • Alireza Bijantabar
    Alireza Bijantabar almost 2 years
    Dear @mere-development, the question the same as me were looking for the way the relation is made in Laravel in migration time. but all you have described was how to make a table. This line: $table->foreign('user_id')->references('id')->on('users'); was the whole point.