簡體   English   中英

一個模型(用戶)如何只有一個其他模型(例如工作場所),但是該工作場所在Sequelize.js中屬於許多用戶?

[英]How can a model (user) has only one other model (eg workplace), but the workplace belongs to many users in Sequelize.js?

我想有一個模型(也就是用戶)屬於另外一個模型(這應該是工作場所),但在工作場所(如蘋果)應該有一個屬於他們的許多用戶。 如何使用Sequelize做到這一點?

我已經嘗試使用一個User.hasOne(models.Workplace) ,但這只允許每個Workplace擁有一個User,因為它在Workplace表中創建了UserId列。

這是我的用戶模型的代碼:

module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define('User', {
        id: {
            autoIncrement: true,
            primaryKey: true,
            type: DataTypes.INTEGER
        },
        username: {
            type: DataTypes.STRING
        },
        firstname: {
            type: DataTypes.STRING
        }
    }, {})

    User.associate = (models) => {
        models.User.hasOne(models.User)
    }

    return User
}

這是我的工作場所模型的代碼:

module.exports = (sequelize, DataTypes) => {
    const Workplace = sequelize.define('Workplace', {
        id: {
            type: DataTypes.INTEGER,
            autoIncrement: true,
            primaryKey: true
        },
        name: {
            type: DataTypes.STRING
        }
    }, {})

    return Workplace
}

謝謝!

讓我們從較低的角度考慮這個問題。

我假設您使用某種關系數據庫,因為您在它之上使用了Sequelize。

您的要求是用戶只有一個其他模型(例如,工作場所),但是工作場所屬於許多用戶。

它可以被翻譯成user模型有外鍵workplaceId在他們的桌子和workspace在其表的外鍵。

例如, { userId: 1, workspaceId: 1 }, { userId: 2, workspaceId: 1 }, { workspaceId: 1 }將是您期望的。

我們怎樣才能做到這一點?

只需在user模型中設置belongsTo關系即可。 (它在您的表中生成workspaceId

首先考慮數據庫層總是好事,因為畢竟Sequelize只是一個抽象層。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM