簡體   English   中英

Sequelize Model 未關聯到 Post

[英]Sequelize Model is not associated to Post

我正在嘗試解決這個問題,但沒有,這是一個簡單的關系,比如用戶有很多帖子,下面是我的模型。 我急於交付這個項目,我的截止日期太近了? 你能調查一下嗎?

// user.js
import { Model, DataTypes } from "sequelize";
import connection from "../connection";

const initUser = (sequelize, Types) => {
    class User extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate(models) {
            // define association here
        }
    }
    User.init(
        {
            id: {
                type: Types.UUID,
                defaultValue: Types.UUIDV4,
                primaryKey: true,
            },
            first_name: Types.STRING,
            last_name: Types.STRING,
            email: Types.STRING,
            password: Types.STRING,
        },
        {
            sequelize,
            modelName: "User",
            tableName: "users",
            createdAt: "created_at",
            updatedAt: "updated_at",
        }
    );
    User.associate = function (models) {
        User.hasMany(models.Post, { foreignKey: "userId", as: "posts" });
    };
    return User;
};

export default initUser(connection, DataTypes);

和后 model

// post.js
import { Model, DataTypes } from "sequelize";
import connection from "../connection";

const initPost = (sequelize, Types) => {
    class Post extends Model {
        /**
         * Helper method for defining associations.
         * This method is not a part of Sequelize lifecycle.
         * The `models/index` file will call this method automatically.
         */
        static associate(models) {
            // define association here
        }
    }
    Post.init(
        {
            id: {
                type: Types.UUID,
                defaultValue: Types.UUIDV4,
                primaryKey: true,
            },
            title: DataTypes.STRING,
            slug: DataTypes.STRING,
            overview: DataTypes.TEXT,
            userId: {
                type: DataTypes.UUID,
                allowNull: false,
                onDelete: "CASCADE",
                references: {
                    model: "users",
                    key: "id",
                    as: "userId",
                },
            },
        },
        {
            sequelize,
            modelName: "Post",
            tableName: "posts",
            createdAt: "created_at",
            updatedAt: "updated_at",
        }
    );
    Post.associate = function (models) {
        Course.belongsTo(models.Post, { foreignKey: "userId", as: "posts" });
    };
    return Post;
};
export default initPost(connection, DataTypes);

下面是我的查詢

const posts = await Post.findAll({
    order: [["created_at", "DESC"]],
    include: [
        {
            model: User,
            as: "user",
        },
    ],
    where: { userId: userId },
});

但這向我顯示了一個錯誤,例如

“用戶未與 Post 關聯!”

出了什么問題我想不通。

謝謝

您應該在models文件夾中創建一個名為index.js的文件,如下所示

import User from "./user";
import Post from "./post";

User.hasMany(Post, { foreignKey: "userId", as: "posts" });
Post.belongsTo(User, { foreignKey: "userId", as: "user" });


export { User, Post };

在 API 中,如下所示

import { Post, User } from "db/models";

const posts = await Post.findAll({
    order: [["created_at", "DESC"]],
    include: [
        {
            model: User,
            as: "user",
        },
    ],
    where: { userId: userId },
});

希望它會有所幫助。

暫無
暫無

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

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