在Gorm查询中给主表起一个别名。

huangapple go评论88阅读模式
英文:

Alias the main table's name in a Gorm query

问题

我有一个类似的 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

生成的查询语句如下:

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

我尝试指定别名 t,但 Gorm 没有识别到它!因此,MySQL 无法理解首先是什么意思的 t

据我所见,文档中没有说明如何指定表别名。

有没有办法在查询中避免使用完整的表名?

英文:

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?

答案1

得分: 4

尝试使用:

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

Try using:

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

huangapple
  • 本文由 发表于 2021年10月3日 23:17:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/69426194.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定