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

fix belongto relationship #79

Open
wants to merge 7 commits into
base: master
Choose a base branch
from

Conversation

rizkyseptiawan
Copy link

@rizkyseptiawan rizkyseptiawan commented Jul 7, 2024

Add a table alias when sorting to the belongsTo, hasOne, and hasMany relation. This is to prevent errors when the main table and child table (sort subquery) have the same table name. For example: the users table has a created_by_id column, where the created_by_id column also refers to the users table.

@Lakshan-Madushanka
Copy link
Collaborator

@rizkyseptiawan Two tables cannot have same name, you might have meant self join but I don't think it would be a issue as we use framework methods to access to keys.

@rizkyseptiawan
Copy link
Author

@Lakshan-Madushanka Yes, I mean self join. As I said, one example case is when I have a users table and in that column for example there is a column that does a self join (created_by_id). In the code that I have pulled request, I have included to replace the table obtained from the framework methods to match the alias name

@Lakshan-Madushanka
Copy link
Collaborator

Then what would be the query string ?

@Lakshan-Madushanka
Copy link
Collaborator

Lakshan-Madushanka commented Jul 9, 2024

@rizkyseptiawan I don't think we can do a self join using just a query string and adding table aliases doesn't make sense to me. You have to define a relationship or use query scopes.
As a example following may get a users(name, city) from different cities.

Users extends Model {

 public function scopeFromDifferentCities(Builder $query) {
   $query->join('users as u2', 'users.id', '<>', 'u2.id')
      ->whereColumn('users.city', 'u2.city')
      ->distict()
 }

}

User::fromDifferentCities()->get()

If I have mistaken,

Actually your title and description is very misleading and subtle and you should use real world scenario like above and example code blocks to explain something complex like this. Finally you should implement test cases to prove what your doing is right and understandable.

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 this pull request may close these issues.

2 participants