-2

When I create a one-to-one relationship migration, laravel creates a one-to-many relationship. I tried to solve this in different ways and nothing worked.
How can I solve this?

Company:

class Company extends Model
{
    public function user()
    {
        return $this->hasOne(User::class);
    }
    ...
}

User:

class User extends Authenticatable
{
    public function company(){
        return $this->belongsTo(Company::class);
    }
    ...
}

Migrations:

Schema::create('Company', function (Blueprint $table) {
            $table->mediumIncrements('idCompany');
            ...
        });

Schema::create('User', function (Blueprint $table) {
            $table->id(); 
            $table->increments('idUser');
            $table->unsignedMediumInteger('Company_idCompany')
                  ->unique()
                  ->nullable();
            $table->foreign('Company_idCompany')
                  ->references('idCompany')
                  ->on('company')
                  ->onDelete('set null');
            ...
        });

Entity diagram

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43
  • What exactly makes it a one-to-many here? Your foreign key field has a unique index so it's impossible to have a company associated with multiple users. I think your ER visualisation program here is just misidentifying the relationship – apokryfos Aug 08 '22 at 04:59
  • @apokryfos MySQL Workbench and PhpMyAdmin show the same one-to-many relationship – TomaszOleszko Aug 08 '22 at 09:23

1 Answers1

0

Laravel is creating nothing (on the migration), you always have to manually create the Model relationship (you are using hasOne and belongsTo, so that is 1-to-1) and migrations (you are creating User and Company not following the standards).

So, update your migrations to:

Schema::create('company', function (Blueprint $table) {
    $table->id();
    ...
});

Schema::create('user', function (Blueprint $table) {
    $table->id(); 
    $table->increments('user_id');
    $table->foreignId('company_id')
        ->unique()
        ->nullable();
    $table->foreign('company_id')
        ->references('id')
        ->on('company')
        ->onDelete('set null');
    ...
});

See that I have moved everything to lowercase and snake case, remember to follow Laravel conventions or you are going to have a harder time working with Models...

Then, your relationships are correct:

class Company extends Model
{
    public function user()
    {
        return $this->hasOne(User::class);
    }
    ...
}

class User extends Authenticatable
{
    public function company(){
        return $this->belongsTo(Company::class);
    }
    ...
}

So, when you do access a relationship, it will work out of the box now.

If you do Company::first()->user, that will return User or null, and if you do User::first()->company, that will return Company or null, there is no 1-to-N.

matiaslauriti
  • 7,065
  • 4
  • 31
  • 43