Home  >  Q&A  >  body text

Does GORM support IIF functions using SQL?

<p>I have a table for assignments, a table for solutions, and a table for students. I want to retrieve all assignments, and for each assignment I want to add a "flag" that shows if the currently logged in student has attempted the assignment. </p> <p>I tried this: </p> <pre class="brush:golang;toolbar:false;">import ( "fmt" "gorm.io/gorm" "encoding/json" "github.com/my_organisation/myorg-repo/db" ) var database *gorm.DB var solutions[]db.Solution var listOfAsnmtIDs []uint func myfuncn (w http.ResponseWriter, r *http.Request){ //... _ = database.Table("solutions").Where("pupil_id = ?", pupil.ID).Select("assignment_id").Find(&solutions) for _, solution := range solutions { listOfAsnmtIDs = append(listOfAsnmtIDs, solution.AssignmentID) } response := database.Table("assignments").Select(`id, created_at, IIF((id IN ?), 'attempted', 'Not attempted') as attempted`, listOfAsnmtIDs).Find(&allAssignments) if response.RowsAffected < 1 { respondToClient(w, 404, nil, "No assignments found") return } //... } </pre></p>
P粉547362845P粉547362845435 days ago584

reply all(1)I'll reply

  • P粉718730956

    P粉7187309562023-09-02 09:29:54

    You only need to list the parameters. Similar to this

        var mad string
        for i, solution := range solutions {
            mad += strconv.FormatUint(uint64(solution.AssignmentID), 10)
            if i != len(solutions) {
                mad += ","
            }
            listOfAsnmtIDs = append(listOfAsnmtIDs, solution.AssignmentID)
        }
    
        response := database.Table("assignments").Select(`id, created_at, IIF((id IN ?), 'attempted', 'Not attempted') as attempted`, mad).Find(&allAssignments)
    

    reply
    0
  • Cancelreply