-
Notifications
You must be signed in to change notification settings - Fork 0
/
tutorial_5.go
48 lines (39 loc) · 1.23 KB
/
tutorial_5.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//go:build tutorial_5
// +build tutorial_5
package main
import (
"fmt"
"log"
"github.com/FrancoLiberali/cql"
"github.com/FrancoLiberali/cql-tutorial/conditions"
"github.com/FrancoLiberali/cql-tutorial/models"
"gorm.io/gorm"
)
// Target: get all cities whose name is 'Paris' and preload its country
func tutorial(db *gorm.DB) {
cities, err := cql.Query[models.City](
db,
conditions.City.Name.Is().Eq("Paris"),
conditions.City.Country().Preload(),
).Find()
// SQL executed:
// SELECT cities.*,
// Country.id AS Country__id,Country.created_at AS Country__created_at,Country.updated_at AS Country__updated_at,Country.deleted_at AS Country__deleted_at,Country.name AS Country__name,Country.capital_id AS Country__capital_id
// FROM cities
// LEFT JOIN countries Country ON
// Country.id = cities.country_id AND Country.deleted_at IS NULL
// WHERE cities.name = "Paris" AND cities.deleted_at IS NULL
if err != nil {
log.Panicln(err)
}
fmt.Println("--------------------------")
fmt.Println("Cities named 'Paris' are:")
for i, city := range cities {
fmt.Printf("\t%v: %+v with country: ", i+1, city)
cityCountry, err := city.GetCountry()
if err != nil {
log.Panicln(err)
}
fmt.Printf("%+v\n", cityCountry)
}
}