我需要使用Knex搜索数据库,只返回给定城市的销售额。为此,
我有两个表:
sale:
id
drugstore_id
drugstore:
id
name
city
我的模型:
class Sale extends Model {
static modelPaths = [__dirname]
static get tableName() {
return 'sale'
}
static relationMappings = {
drugstore: {
relation: Model.BelongsToOneRelation,
modelClass: Drugstore,
join: {
to: 'drugstore.id',
from: 'sale.drugstore_id',
},
},
}
}
class Drugstore extends Model {
static get tableName() {
return 'drugstore'
}
static relationMappings = {
sale: {
relation: Model.HasManyRelation,
modelClass: Sale,
join: {
to: 'sale.drugstore_id',
from: 'drugstore.id',
},
},
}
}
我像这样运行查询:
this.repository
.query()
.select('id', 'drugstore_id')
.withGraphFetched('[drugstore(drugstoreByCity, drugstoreSelect)]')
.modifiers({
drugstoreByCity(builder) {
builder.where('city', 'Sorocaba')
},
drugstoreSelect(builder) {
builder.select('name', 'city')
},
})
返回如下数组:
[
{
"id": 1503,
"drugstore_id": "36",
"drugstore": {
"name": "Farmácia Teste",
"city": "Sorocaba"
}
},
{
"id": 1502,
"drugstore_id": "14",
"drugstore": null
}
]
返回第一个对象,因为城市与"Sorocaba"相同,然而,第二个对象也返回,但第二个对象的城市不同。我需要的是它只返回某一城市药店的销售。
我相信这可能是异议本身的限制,根据文档:
"关系不能在根查询中引用,因为它们不是加入!"https://vincit.github.io/objection.js/api/query-builder/eager-methods.html withgraphfetched
我需要用另一种方式来执行这个查询,使用连接而不是急切加载。