laravelforeign-keysprimary-keyshared-primary-key

How to define and use a foreign key as primary key in Laravel?


I have a Users table that can store 8 different types of users. Depending on the user type, I have some other tables with the specific data set for it. So, I would like to use the ID from the Users table as a foreign key and primary key at the same time for those tables. But I am new at Laravel and I don't know how to do that to fit the conventions or, if it is not possible, how to do that when defining my models and one to one relations. Can someone help me? Thanks!

EDIT: Sorry, I think my explanation is not clear enough. Let's say I have 4 tables: users, user_types, customer_organzations, partners, and customers. I would like to use ID, that is PK of users, as a foreign key and primary key for tables customer_organizations, partners and customers, that have different information since they are different type of users in my application but all them login against users table. I don't care user_types table. I think I know how to deal with it.


Solution

  • You haven't given us much in terms of your table structure, so assuming you have a simple one-to-one relationship between a users table and a user_types table, the following would create the required relationship.

    In your user_types table migration

    $table->foreignId('user_id')->constrained();
    

    The above will add your foreign key to the table and create the relationship back to the users table (this is done 'magically' using conventions so naming is important).

    Then in your eloquent models, add the relationships between the models:

    User.php

    public function type()
    {
        return $this->hasOne(UserType::class);
    }
    

    UserType.php

    public function user()
    {
        return $this->belongsTo(User::class);
    }