Skip to content

Instantly share code, notes, and snippets.

@anti1869
Created August 4, 2018 19:27
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anti1869/84b994692c1b0b2de58446cba328026d to your computer and use it in GitHub Desktop.
Save anti1869/84b994692c1b0b2de58446cba328026d to your computer and use it in GitHub Desktop.
Join two structs on foreign key relation with jmoiron/sqlx (nested json object from struct)
/*
Note: I have db.MapperFunc(FromCamelCaseToUnderScore)
This will make nested json like this
{
"likes": [
{
"chat_id": 155636374,
"created": "2018-08-04T10:52:36.360217Z",
"from": {
"id": 1,
"rating": 11,
"username": "anti1869"
},
"id": 21,
"like_msg": "+",
"question_msg": "",
"reply_msg": "+",
"to": {
"id": 1,
"rating": 11,
"username": "anti1869"
}
}
]
}
*/
package web
import (
"github.com/kataras/iris"
"somewhere.com/somewhere/config"
"log"
)
type LikeList struct {
Likes []Like `json:"likes"`
}
type Like struct {
Id int `json:"id"`
ChatId int64 `json:"chat_id"`
Created string `json:"created"`
LikeMsg string `json:"like_msg"`
ReplyMsg string `json:"reply_msg"`
QuestionMsg string `json:"question_msg"`
From User `json:"from" db:"from"`
To User `json:"to" db:"to"`
}
func GetLikeListhandler(ctx iris.Context){
result := LikeList{}
q := ` SELECT
l.id, l.chat_id, l.created, l.like_msg, l.reply_msg,
uf.id "from.id",
uf.username "from.username",
uf.rating "from.rating",
ut.id "to.id",
ut.username "to.username",
ut.rating "to.rating"
FROM likes l
JOIN users uf ON l.from_id = uf.id
JOIN users ut ON l.to_id = ut.id
ORDER BY created DESC`
rows, err := config.Db.Queryx(q)
if err != nil {
log.Fatal(err)
}
defer rows.Close()
for rows.Next() {
var l Like
err = rows.StructScan(&l)
if err != nil {
log.Print(err)
}
result.Likes = append(result.Likes, l)
}
err = rows.Err()
if err != nil {
log.Panic(err)
}
ctx.JSON(result)
}
@shawnshuang
Copy link

@anti1869 Thanks for putting this together. It helped me figure out an issue I was running into.

I know it's been awhile since you wrote this, but would you happen to remember what allows for the "from.id", "from.username", etc syntax in the SELECT query? Is it the standard database/sql package that is allowing for that syntax? Or is it some other package like lib/pq or jmoiron/sqlx?

@johnmaguire
Copy link

johnmaguire commented Mar 15, 2023

@anti1869 Thanks for putting this together. It helped me figure out an issue I was running into.

I know it's been awhile since you wrote this, but would you happen to remember what allows for the "from.id", "from.username", etc syntax in the SELECT query? Is it the standard database/sql package that is allowing for that syntax? Or is it some other package like lib/pq or jmoiron/sqlx?

I know this is years late, but it's just SQL. MySQL supports aliasing columns without using the AS keyword.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment