[英]Alias the main table's name in a Gorm query
I have a Gorm query similar to:我有一个类似于以下的 Gorm 查询:
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!我试图指定的别名
t
没有被 Gorm 拾取! Therefore MySQL doesn't understand what t
is in first place.因此 MySQL 首先不理解
t
是什么。
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?有什么办法可以避免在查询中使用全名?
Try using:尝试使用:
db.Table(model.BlogTag{}.TableName() + "AS t")
That works well in my projects.这在我的项目中效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.