【问题标题】:The foreign key connection field is queried twice外键连接字段被查询两次
【发布时间】:2021-11-01 15:03:21
【问题描述】:

我有两张表,一张是关于文章的,另一张是关于 cmets 的

//this is the table model of articles
module.exports = (app) => {
    const { STRING, INTEGER, DATE } = app.Sequelize;

    const Model = app.model.define(
        "all_topics",
        {
            id: { type: INTEGER, primaryKey: true, autoIncrement: true },
            title: STRING(30),
            content: STRING,
            user_id: INTEGER,
            created_at: DATE,
            updated_at: DATE,
            tag: STRING(30),
        },
        {
            underscored: true,
        }
    );

    Model.associate = function () {
        Model.belongsTo(app.model.Users, { foreignKey: "user_id" });
        Model.hasMany(app.model.Comments, {
            foreignKey: "topic_id",
            sourceKey: "id",
        });
    };

    return Model;
};
//this is the table model of comments
module.exports = (app) => {
    const { STRING, INTEGER, DATE } = app.Sequelize;

    const Model = app.model.define(
        "comments",
        {
            id: { type: INTEGER, primaryKey: true, autoIncrement: true },
            topic_id: INTEGER,
            user_id: INTEGER,
            parent_id: INTEGER,
            content: STRING,
            created_at: DATE,
        },
        {
            timestamps: false,
            freezeTableName: true,
            underscored: true,
        }
    );

    Model.associate = function () {
        Model.belongsTo(app.model.Users, {
            foreignKey: { user_id: "id", parent_id: "id" },
        });
        Model.belongsTo(app.model.AllTopics, {
            foreignKey: "topic_id",
            sourceKey: "id",
        });
    };

    return Model;
};
//Query the article that specifies the id and the comments it contains
const Service = require("egg").Service;

class TopicLoadService extends Service {
    async topicLoad(id) {
        const { ctx } = this;
        const topic = await ctx.model.AllTopics.findOne({
            where: {
                id,
            },
            include: [{ model: ctx.model.Comments }],
        });
        return { topic };
    }
}

module.exports = TopicLoadService;

已经在 MySQL 数据库中设置了外键 但是,返回错误:'field list'中的未知列'cmets.userId'

它执行的查询语句是

SELECT `all_topics`.`id`, 
       `all_topics`.`title`, 
       `all_topics`.`content`, 
       `all_topics`.`user_id`, 
       `all_topics`.`created_at`, 
       `all_topics`.`updated_at`, 
       `all_topics`.`tag`, 
       `comments`.`id` AS `comments.id`, 
       `comments`.`topic_id` AS `comments.topic_id`, 
       `comments`.`user_id` AS `comments.user_id`,       //Queried
       `comments`.`parent_id` AS `comments.parent_id`, 
       `comments`.`content` AS `comments.content`,     
       `comments`.`created_at` AS `comments.created_at`, 
       `comments`.`user_id` AS `comments.userId`       //Why is this another query?
FROM `all_topics` AS `all_topics` 
LEFT OUTER JOIN `comments` AS `comments` 
ON `all_topics`.`id` = `comments`.`topic_id` 
WHERE `all_topics`.`id` = '20000000';

我是新手,有些知识没有掌握,可以帮我解答吗?非常感谢

【问题讨论】:

  • 能否在你的数据库中包含 cmets 表的定义?例如,您可以写一个CREATE TABLE comments ( ... ); 语句并将其添加到问题中吗?这将使解决此问题变得更加容易......
  • 对不起,我用的是Navicat,所以我没有使用语句。(准确地说,我不能通过语句创建表,很尴尬)。表的结构与上面的模型。
  • 外键是CONSTRAINT com_user_id FOREIGN KEY(user_id) REFERENCES users(id)),CONSTRAINT parent_id FOREIGN KEY(parent_id) REFERENCES users(id)),CONSTRAINT topic_id FOREIGN KEY(topic_id) REFERENCES all_topics(id))。外键属于 cmets 表。谢谢
  • em...其实现在已经没有错误了。但是,返回结果中有user_id和userId(重复数据)如果我不设置underscored: true会报错:"Unknown column 'cmets.userId' in 'field list'"
  • 没关系,魏。即使使用 Navicat,也应该可以获得数据库中 articles 和 comments 表中的列列表,以及每列的数据类型。如果您可以在问题中发布列名及其数据类型(或至少是您尝试映射的数据类型),那么有人可能更容易确认您的 javascript 中的 sequelize 定义正确地将您的模型映射到数据库结构。

标签: javascript sequelize.js egg


【解决方案1】:

需要注意的几点:

  1. foreignKey 属性通常采用表示外键列名的字符串。还有另一个属性称为 sourceKey 或 targetKey,这取决于它是缺少联结表的 has 还是 belongs 关系,它表示引用的键。
  2. sequelize 的模型名通常为单数,数据库中表的名称为复数。这是一个很好的约定,因为模型实例最终会使用Foo.addBar 和Foo.addBars 等辅助方法来在数据库中创建新的子行。请参阅sequelize docs 了解更多信息。
  3. 模型定义中缺少一些属性。它们可能不是让事情正常运行所必需的,但这样您的模型将更紧密地映射到数据库中的相应结构。

试试这个:

// articles
module.exports = (app) => {
    const { STRING, INTEGER, DATE } = app.Sequelize;

    const Model = app.model.define(
        "all_topic", // Following sequelize convention, it might be better to have the model name be singular,
                     //  i.e. "all_topic", instead of "all_topics"....
        {
            id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
            title: { type: STRING(30), allowNull: false },
            content: { type: STRING, defaultValue: null },
            user_id: { type: INTEGER, references: { model: app.model.Users, key: 'id' }, allowNull: false },
            created_at: { type: DATE, defaultValue: null, allowNull: true },
            updated_at: { type: DATE, defaultValue: null, allowNull: true },
            tag: { type: STRING(30), allowNull: false },
        },
        {
            tableName: "all_topics",
            underscored: true
        }
    );

    Model.associate = function () {
        Model.belongsTo(app.model.Users, {
            foreignKey: "user_id",
            targetKey: "id",
            onDelete: "RESTRICT",
            onUpdate: "RESTRICT"
        });
        Model.hasMany(app.model.Comments, {
            foreignKey: "topic_id",
            sourceKey: "id",
            onDelete: "RESTRICT",
            onUpdate: "RESTRICT"
        });
    };

    return Model;
};

对于 cmets 模型:

// comments
module.exports = (app) => {
    const { STRING, INTEGER, DATE } = app.Sequelize;

    const Model = app.model.define(
        "comment", // Following sequelize convention, it might be better to have the model name be singular,
                   //  i.e. "comment", instead of "comments"....
        {

            id: { type: INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
            topic_id: { type: INTEGER, allowNull: false },
            user_id: { type: INTEGER, allowNull: false, references: { model: app.model.Users, key: 'id' } },
            parent_id: { type: INTEGER, allowNull: false, references: { model: app.model.Users, key: 'id' } },
            topic_id: { type: INTEGER, allowNull: false, references: { model: app.model.AllTopics, key: 'id' } },
            content: { type: STRING, allowNull: false },
            created_at: { type: DATE, allowNull: false },
        },
        {
            timestamps: false
        }
    );

    Model.associate = function () {
        Model.belongsTo(app.model.Users, {
            foreignKey: "user_id",
            targetKey: "id",
            as: "user",
            onDelete: "RESTRICT",
            onUpdate: "RESTRICT"
        });
        Model.belongsTo(app.model.Users, {
            foreignKey: "parent_id",
            targetKey: "id",
            as: "parent",
            onDelete: "RESTRICT",
            onUpdate: "RESTRICT"
        });
        Model.belongsTo(app.model.AllTopics, {
            foreignKey: "topic_id",
            sourceKey: "id",
            onDelete: "RESTRICT",
            onUpdate: "RESTRICT"
        });
    };

    return Model;
};

简单介绍一下sequelize timestamps。可以启用时间戳并为列提供自定义名称。根据文档:

也可以只启用 createdAt/updatedAt 之一,然后 为这些列提供自定义名称:

class Foo extends Model {}
Foo.init({ /* attributes */ }, {  
  sequelize,

  // don't forget to enable timestamps!
  timestamps: true,

  // I don't want createdAt
  createdAt: false,

  // I want updatedAt to actually be called updateTimestamp  
  updatedAt: 'updateTimestamp' });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 2012-05-15
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多