Using a subquery in 'FROM' in gorm

后端 未结 6 1451
梦谈多话
梦谈多话 2021-02-10 03:03

I would like to know how I can use a subquery in FROM clause using gorm. It would look like the following:

SELECT * FROM 
(
  SELECT foo.*
  FROM foo
  WHERE bar         


        
6条回答
  •  青春惊慌失措
    2021-02-10 03:21

    Solved this issue by creating a package for more flexibility: https://github.com/loeffel-io/sql

    subquery := sql.Create().
        Select(true, "purchases.*").
        Select(true, "...").
        From(true, "purchases").
        Join(true, "transactions ON transactions.purchase_id=purchases.id")
    
    query := sql.Create().Select(true, "*").
        From(true, "(?) purchases", gorm.Expr(subquery.GetSQL(), subquery.GetValues()...)).
        Join(true, "transactions ON transactions.id=purchases.last_transaction_id")
    
    db.
        Raw(query.GetSQL(), query.GetValues()...).
        Offset(...).
        Limit(...).
        Order(...).
        Unscoped().
        Find(&purchases).
        Error
    

提交回复
热议问题