Search code examples
mysqlgogo-gorm

Alias the main table's name in a Gorm query


I have a Gorm query similar to:

db.
    Table(fmt.Sprintf("%s t", model.BlogTag{}.TableName())).
    Select(`
        t.id,
        t.path,
        t.title,
        t.hits,
        COUNT(DISTINCT b.id) AS used_times
    `).
    Joins("LEFT JOIN contentitem_tag_map bt ON bt.tag_id = t.id").
    Joins("LEFT JOIN content b ON b.id = bt.content_item_id AND b.state = 1").
    Where("t.published = 1").
    Group("t.id").
    Order("used_times DESC").
    Find(&tags).Error

The resulting query looks like:

SELECT t.id, t.path, t.title, t.hits, COUNT(DISTINCT b.id) AS used_times
FROM `myschema`.`vk9wz_tags` 
LEFT JOIN myschema.vk9wz_contentitem_tag_map bt ON bt.tag_id = t.id 
LEFT JOIN myschema.vk9wz_content b ON b.id = bt.content_item_id AND b.state = 1 
WHERE t.published = 1 
GROUP BY `t`.`id` 
ORDER BY used_times DESC

The alias t I tried to specify is not picked up by Gorm! Therefore MySQL doesn't understand what t is in first place.

The documentation doesn't include how to specify the table alias, as far as I can see.

Is there any way I can avoid using the full name in my query?


Solution

  • Try using:

    db.Table(model.BlogTag{}.TableName() + " AS t")