访问辅助实体的属性

问题描述 投票:0回答:3

有人可以帮我解决以下问题吗? 在下面的 Gosu 代码中,如何在查询结果中包含地址表中的城市信息(无需翻转表格 - 从地址表开始)?地址表有一个指向用户表的外键,但其他方向没有外键。行查询可以做到这一点吗? 非常感谢

uses gw.api.database.Query

// -- query the User entity --
var queryUser = Query.make(User)

// -- select only User instances who last updated addresses in the city of Chicago --
var tableAddress = queryUser.join(Address, "UpdateUser")
tableAddress.compare("City", Equals, "Chicago") 

// -- fetch the User instances with a for loop and print them --
var result = queryUser.select()

for (user in result) {
    print (user.DisplayName)
}
gosu guidewire
3个回答
1
投票

显然,您可以在数据库中进行创建双向关系的配置。这有一定的风险和一定的数据库开销,这可能是有道理的,也可能不是。

填补单向关系空白的另一种半标准方法是在 Gosu 增强上使用 getter 属性。该属性将使用增强 ID 作为查询 ID 来执行查询。您的用例是只读的,这使得解决方案相当简单。您必须确保查询表上的匹配列已建立索引。性能应该不错,因为查询将使用 OOTB DB 缓存。

如果您的用例更加通用,您可能希望开始保持增强实体的捆绑与查询结果一致。 您可以将查询实体行添加到增强实体的捆绑包中,使其看起来更像一个真实的财产。如果这样做,您应该在执行查询之前询问捆绑包以确保查询实体行尚未在捆绑包中。

如果查询实体有更新,假设访问属性时增强实体已经处于事务中,它们将正常工作。

当然,这一切都不是完美的。返回 FK 没有添加到增强型实体中可能有充分的理由。添加一个执行类似于数据库支持实体的查询的属性需要一些小心和喂养。


0
投票

既然Address有用户FK为什么不扭转局面呢?

uses gw.api.database.Query

// -- query the Address entity --
var queryAddress = Query.make(Address)
queryAddress.compare("City", Equals, "Chicago") 

// -- select only User instances who last updated addresses in the city of Chicago --
var tableUser = queryAddress.join(Address#UpdateUser)

// -- fetch the Addresses instances with a for loop and print them --
var result = tableUser.select()

for (address in result) {
    print(address.City?.DisplayName)
    print(address.UpdateUser?.DisplayName)
}

0
投票

是的,可以,只需按以下方式链接即可

uses gw.api.database.Query

var result = Query.make(User)
.join(Address#UpdateUser)
.compare("City", Equals, "Chicago").select()

for (user in result) {
    print (user.DisplayName)
}
© www.soinside.com 2019 - 2024. All rights reserved.