我正在研究
sequalize association - hasOne
变体。我从 USER
表中获取了所有行,而不是从 system_admin
表中返回行。这是预期的行为吗?
const User = sq.define('user', {
firstName: {type: DataTypes.STRING, allowNull: false },
lastName: {type: DataTypes.STRING, allowNull: false },
email: {type: DataTypes.STRING, allowNull: false },
password: {type: DataTypes.STRING, allowNull: false },
phoneCode: {type: DataTypes.STRING, allowNull: false },
phone: {type: DataTypes.STRING, allowNull: false },
is_deleted: {type: DataTypes.BOOLEAN, defaultValue: false },
is_active: {type: DataTypes.BOOLEAN, defaultValue: true }
}, {
tableName: 'users',
indexes: [
{
unique: true,
fields: ['email', 'is_deleted', 'is_active']
}
]
});
const SystemAdmin = sq.define('system_admin', {
categories_id: {type: DataTypes.BIGINT, allowNull: false },
user_id: {type: DataTypes.BIGINT, allowNull: false },
is_deleted: {type: DataTypes.BOOLEAN, defaultValue: false }
}, { tableName: 'system_admin'});
User.hasOne(SystemAdmin, { as: "system_admin", foreignKey: "user_id", });
SystemAdmin.belongsTo(User, {
foreignKey: "id",
as: "users",
});
const userss = await User.findAll({ include: ["system_admin"] });
console.log(userss.length);
我从
findAll
方法获取所有用户行。您能否建议适当的语法来仅获取系统管理员用户行?
谢谢
您只需要使用
include
选项的扩展语法并指示您需要 INNER JOIN(即一个表中的所有记录应在另一表中具有相关记录):
const userss = await User.findAll({ include: [{
model: SystemAdmin,
// true - INNER JOIN, false - LEFT OUTER JOIN
required: true
}] });
在这种情况下,
hasOne
显示您可以获取所有用户,但可能并非所有用户都在SystemAdmin
中拥有相应的记录,因此您需要明确指示您只需要那些在SystemAdmin
中拥有记录的用户。