Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HasOne and HasMany relationship arguments are interchanged. #43

Open
adwiv opened this issue Dec 16, 2024 · 0 comments · May be fixed by #49
Open

HasOne and HasMany relationship arguments are interchanged. #43

adwiv opened this issue Dec 16, 2024 · 0 comments · May be fixed by #49

Comments

@adwiv
Copy link
Contributor

adwiv commented Dec 16, 2024

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.

adwiv added a commit to adwiv/laravel-crud-generator that referenced this issue Dec 17, 2024
@adwiv adwiv linked a pull request Dec 17, 2024 that will close this issue
adwiv added a commit to adwiv/laravel-crud-generator that referenced this issue Dec 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant