Skip to content

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