在 GoFrame ORM 中,可以使用 LeftJoin、RightJoin 和 InnerJoin 方法来执行左连接、右连接和内连接操作。这些方法允许你在查询中联接多个表,根据指定的条件进行关联查询。

LeftJoin 左连接

左连接返回左表中的所有行,以及右表中匹配的行。如果右表中没有匹配的行,将返回空值。
package main

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

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

// 左连接查询
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 方法进行左连接查询,将 user 表与 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()

// 右连接查询
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 方法进行右连接查询,将 user 表与 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()

// 内连接查询
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 方法进行内连接查询,将 user 表与 profile 表关联,通过 profile.user_id = user.id 来指定关联条件。

这些方法可以根据实际需求在查询中进行表的关联操作,使得查询结果包含来自多个表的数据。


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