Your Question

I want to add TABLE ALIAS using db.Model but i did not find anything in documentation. So how do i add table alias "users as u" using models query db.Model(&User{}).Select("users.name") ?

Same i can do with db.Table("users as u").Select("users.name")

The document you expected this should be explained

https://gorm.io/docs/query.html#Joins

Expected answer

Should be able to add table alias users as u using models query

Comment From: jinzhu

You need to write it like this

db.Table("users as u").Select("u.name")

Comment From: khanakia

@jinzhu Yes this one i know. But for this i have to hardcode users. Is there any way to add alias using db.Model(&User{})

Comment From: iTanken

tx.Table("(?) AS U", db.Model(&User{}))

Comment From: abbychau

(&model.Session{}).TableName()+" as FORCE_SLAVE"

Comment From: ezk84

This is still not really addressed by any of the answers:

(&model.Session{}).TableName()+" as FORCE_SLAVE" relies on the model having implemented the TableName() method.

tx.Table("(?) AS U", db.Model(&User{})) creates a subquery, which isn't what we wanted.

Finally, using db.Table("users as u").Select("u.name") forces us to hard code the table name users, when Model lets gorm decide the table name based on the db.NamingStrategy.

Internally, gorm translates a Model name to a table name, we either need to be able to access this derived table name to be able to use the Table function, or have a way to give an alias to the model selected with the Model function.

Comment From: ZacharyBear

You need to write it like this

go db.Table("users as u").Select("u.name")

When I used the alias t_log AS l, the * is not allowed:

"column l.* does not exist"

I have to define each field for the main table ...