gpt4 book ai didi

javascript - 如何在 objection.js 中为模型的所有查询自动包含 `.withGraphFetched()`

转载 作者:行者123 更新时间:2023-12-05 02:55:06 24 4
gpt4 key购买 nike

我定义了以下模型:

import db from "../connection.js";
import objection from "objection";
const { Model } = objection;

Model.knex(db);

class User extends Model {
static get tableName() {
return "users";
}

static get relationMappings() {
return {
emails: {
relation: Model.HasManyRelation,
modelClass: Email,
join: {
from: "users.id",
to: "emails.user_id",
}
}
}
}
}

class Email extends Model {
static get tableName() {
return "emails";
}

static get relationMappings() {
return {
user: {
relation: Model.BelongsToOneRelation,
modelClass: User,
join: {
from: "emails.user_id",
to: "users.id",
},
},
};
}
}

要使用电子邮件地址查询用户,需要每次显式运行withGraphFetched(),如下所示:

const myUser = await User.query().withGraphFetched("emails").findById(1)

我一直无法弄清楚要在模型定义中写些什么才能使这成为可能,而且我在网上也没有看到任何此类示例。是否可以始终将 withGraphFetched("emails") 自动包含在查询中,这样就不必每次都明确写出来?

最佳答案

这样的东西不存在。也许您可以在 beforeFind 中创建逻辑hook 将 eager loader 添加到 knex 实例,但它可能会产生许多不希望的和奇怪的副作用。

通常的做法是为特定情况添加一个方法:

class User extends Model {
static get tableName() {
return "users";
}

static get relationMappings() {
return {
emails: {
relation: Model.HasManyRelation,
modelClass: Email,
join: {
from: "users.id",
to: "emails.user_id",
}
}
}
}

static async getUser (id) { // Or maybe getUserWithEmails
return await this.query().withGraphFetched("emails").findById(id)
}
}

然后你可以:

const myUser = await User.getUser(id)

关于javascript - 如何在 objection.js 中为模型的所有查询自动包含 `.withGraphFetched()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61515674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com