gpt4 book ai didi

sequelize.js - 在 Sequelize 中总是渴望加载关系

转载 作者:行者123 更新时间:2023-12-03 22:36:23 24 4
gpt4 key购买 nike

我已经尝试搜索这个问题,我没有找到解决方案。

在 Laravel (PHP) 中,您可以在 ORM (Eloquent) 模型上定义以下内容:

class User extends Eloquent
{
protected $with = ['roles'];
}

在示例中,查询 User 将始终预先加载 roles 关系(示例中未定义)。

我想对 Node.js 的 Sequelize.js 做同样的事情。

你能定义自动加载(包含)关系吗?

最佳答案

您可以使用 scopes 来实现这一点,它们支持 include 并且您可以定义 defaultScope

例如(代码未经测试,但应该让您知道您需要在自己的代码中实现它):

const Role = sequelize.define('role', { 
name: DataTypes.STRING,
}, {
timestamps: false,
});

const User = sequelize.define('user', {
name: DataTypes.STRING
}, {
timestamps: false,
defaultScope: {
include: Role,
},
});

User.hasMany(Role);
Role.belongsTo(User);

关于sequelize.js - 在 Sequelize 中总是渴望加载关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59878865/

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