Skip to content

HasOne and HasMany relationship arguments are interchanged. #43

Open
@adwiv

Description

@adwiv

When we generate a model, its relationships of type HasOne and HasMany has the foreign_key and owner_key parameters interchanged.

You can reproduce this with the test repository - https://github.com/adwiv/crud-gen-test-1. In this repo, we have added a migration for phones table which has a user_id foreign key. Thus a user can have multiple phone numbers.

When generating the User model (api only), the relation is generated like this:

public function phones()
{
    return $this->hasMany(\App\Models\Phone::class, 'id', 'user_id');
}

However the correct order of arguments is

 return $this->hasMany(\App\Models\Phone::class, 'user_id', 'id');

The issue can be traced to ModelGenerator#L134. We are looking at foreign keys of a different table, so the foreign_table is actually owner table and the foreign_key is owner_key and vice versa.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions