Your Question

package models

type Employee struct {
    ID              int64 `gorm:"primaryKey"`
    Name            string
    CompanyCustomID int
    Company         Company `gorm:"foreignKey:CompanyCustomID"`
    IDCard          IDCard
}

type Company struct {
    ID   int64 `gorm:"primaryKey"`
    Name string
}

type IDCard struct {
    ID         int64 `gorm:"primaryKey"`
    Name       string
    EmployeeID int64
}
func main() {
    var emp1 = models.Employee{ID: 2}
    DB.Preload("Company").Preload("IDCard").First(&emp1)
    fmt.Println(emp1)
}

Why does the sql log output order not is execute order,it is my go run output

2024-09-02 01:18:33.090601515 +0800 CST m=+0.004264097          181.079µs               SELECT `companies`.`id`,`companies`.`name` FROM `companies` WHERE `companies`.`id` = 2

2024-09-02 01:18:33.090922619 +0800 CST m=+0.004585199          230.957µs               SELECT `id_cards`.`id`,`id_cards`.`name`,`id_cards`.`employee_id` FROM `id_cards` WHERE `id_cards`.`employee_id` = 2

2024-09-02 01:18:33.090942845 +0800 CST m=+0.004605426          1.137411ms              SELECT `employees`.`id`,`employees`.`name`,`employees`.`company_custom_id` FROM `employees` WHERE `employees`.`id` = 2 ORDER BY `employees`.`id` LIMIT 1

The document you expected this should be explained

when i use find method with preload and then it generated multiple sql log to the console,but the order of sql log output made me confusion, and i search from google and baidu, not body talk about the order of the sql log output. so it is default behavior?

Expected answer

i think it the console may be output the order of the sql log like below result

2024-09-02 01:18:33.33.090601515+0800 CST m=+0.004605426          1.137411ms              SELECT `employees`.`id`,`employees`.`name`,`employees`.`company_custom_id` FROM `employees` WHERE `employees`.`id` = 2 ORDER BY `employees`.`id` LIMIT 1
2024-09-02 01:18:33.090922619  +0800 CST m=+0.004264097          181.079µs               SELECT `companies`.`id`,`companies`.`name` FROM `companies` WHERE `companies`.`id` = 2

2024-09-02 01:18:33.090942845 +0800 CST m=+0.004585199          230.957µs               SELECT `id_cards`.`id`,`id_cards`.`name`,`id_cards`.`employee_id` FROM `id_cards` WHERE `id_cards`.`employee_id` = 2

Comment From: MateSoftware2023

same question