使用github.com/go-pg/pg库,通过连接两个表创建更新查询。

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

Create Update query by joining two tables with github.com/go-pg/pg

问题

我正在尝试通过将一些条件与另一个表进行连接来更新我的Postgres表中的一个字段。我参考了这个链接,它给出了一个与我的情况相关的查询模型:

UPDATE product as p SET price = 200 FROM product_segment as ps WHERE p.segment_id = ps.id and p.name = 'diam'

现在我需要将这个查询转换为orm.Query。我尝试使用Join(),但似乎不起作用。

我尝试的代码:

_, err := c.postgresDB.WithContext(ctx).Model(Product).
Set("price =?", 200).
Join("LEFT JOIN product_segment as ps").
JoinOn("ps.id = product.segment_id").
Where("name =?", "diam").
Update()

如何正确编写代码以实现所需的结果??

英文:

I am trying to update one field in my postgres table by joining some conditions with another table. I referred this link, which give me a query model that relates to my scenario:

UPDATE product as p SET price = 200 FROM  product_segment as ps WHERE p.segment_id = ps.id and p.name = 'diam'

Now I have to convert this query in to orm.Query. I tried with Join() but it doesn't seem to work .

the code I tried :

_, err := c.postgresDB.WithContext(ctx).Model(Product).
	Set("price =?", 200).
	Join("LEFT JOIN product_segment as ps").
	JoinOn("ps.id = product.segment_id").
	Where("name =?", "diam").
	Update()

How do I properly write the code to achieve desired result ???

答案1

得分: 0

经过多次尝试,我最终编写了下面的代码,得到了我想要的结果。

_, err := c.postgresDB.WithContext(ctx).Model(Product).
    Set("price =? from product_segment as ps", 200).
    Where("name =?", "diam").
    Update()

如果你们有更好的方法,请分享一下。

英文:

After many tries, I ended up doing the below code which gave me the result I wanted.

_, err := c.postgresDB.WithContext(ctx).Model(Product).
    Set("price =? from product_segment as ps", 200).
    Where("name =?", "diam").
    Update()

Please share if you guys have better methods.

huangapple
  • 本文由 发表于 2022年6月23日 21:57:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/72731431.html
匿名

发表评论

匿名网友

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

确定