简体   繁体   中英

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

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 ???

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM