在 GoFrame ORM 中,模型关联是指在进行查询时,能够方便地关联其他表的数据。GoFrame ORM 提供了一系列链式操作方法来实现模型关联,其中包括 LeftJoin、RightJoin、InnerJoin 等方法。以下是一个简单的模型关联示例:

假设有两个模型:User 和 Profile。
package model

type User struct {
Id   int
Name string
Age  int
}

type Profile struct {
Id     int
UserId int
Email  string
}

LeftJoin 模型关联示例
package main

import (
"fmt"
"github.com/gogf/gf/database/gdb"
"your_project/model"
)

func main() {
// 创建数据库连接
db := gdb.New()

// 左连接查询,关联 Profile 表
result, err := db.Model(&model.User{}).
LeftJoin("profile", "profile.user_id = user.id").
Fields("user.id, user.name, user.age, profile.email").
Where("user.age > ?", 18).
OrderBy("user.age DESC").
Limit(10).
All()

if err != nil {
fmt.Println("查询失败:", err)
return
}

// 处理查询结果
fmt.Println(result)
}

在上述代码中,我们使用 LeftJoin 方法实现了左连接查询,关联了 Profile 表,通过 profile.user_id = user.id 来指定关联条件。

RightJoin 模型关联示例
package main

import (
"fmt"
"github.com/gogf/gf/database/gdb"
"your_project/model"
)

func main() {
// 创建数据库连接
db := gdb.New()

// 右连接查询,关联 Profile 表
result, err := db.Model(&model.User{}).
RightJoin("profile", "profile.user_id = user.id").
Fields("user.id, user.name, user.age, profile.email").
Where("user.age > ?", 18).
OrderBy("user.age DESC").
Limit(10).
All()

if err != nil {
fmt.Println("查询失败:", err)
return
}

// 处理查询结果
fmt.Println(result)
}

在上述代码中,我们使用 RightJoin 方法实现了右连接查询,关联了 Profile 表,通过 profile.user_id = user.id 来指定关联条件。

InnerJoin 模型关联示例
package main

import (
"fmt"
"github.com/gogf/gf/database/gdb"
"your_project/model"
)

func main() {
// 创建数据库连接
db := gdb.New()

// 内连接查询,关联 Profile 表
result, err := db.Model(&model.User{}).
InnerJoin("profile", "profile.user_id = user.id").
Fields("user.id, user.name, user.age, profile.email").
Where("user.age > ?", 18).
OrderBy("user.age DESC").
Limit(10).
All()

if err != nil {
fmt.Println("查询失败:", err)
return
}

// 处理查询结果
fmt.Println(result)
}

在上述代码中,我们使用 InnerJoin 方法实现了内连接查询,关联了 Profile 表,通过 profile.user_id = user.id 来指定关联条件。

这些示例演示了在 GoFrame ORM 中进行模型关联的基本操作。你可以根据实际需求使用不同的关联方法来构建查询语句。


转载请注明出处:http://www.pingtaimeng.com/article/detail/7644/GoFrame