英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论