【问题标题】:Sequelize MySQL select from the same table (left join)Sequelize MySQL 从同一个表中选择(左连接)
【发布时间】:2018-03-30 10:50:46
【问题描述】:

如何使用 Sequelize 从同一张表中选择两次? 这是 MySQL 代码:

select b.*, a.parent_id
from theSameTable as b left join theSameTable as a on b.parent_id = a.id

这是我的 MySQl 表

这是我的 Sequelize 代码

const db = await ec.sequelize.define(tableDb, {
    id: {
        type: ec.Sequelize.INTEGER.UNSIGNED,
        primaryKey: true,
        autoIncrement: true
    },
    url: ec.Sequelize.STRING(511),
    url_hash: ec.Sequelize.STRING(32),
    name: ec.Sequelize.STRING(511),
    full_name: ec.Sequelize.STRING(511),
    parent_id: ec.Sequelize.INTEGER(11).UNSIGNED,
    cnt: ec.Sequelize.STRING(255),
    chk: ec.Sequelize.INTEGER(1)
}, {
    indexes: [{
        unique: true,
        fields: ['url_hash']
    }]
});

await ec.sequelize.sync();

【问题讨论】:

标签: javascript mysql left-join sequelize.js


【解决方案1】:

我终于找到了答案。也许对某人会有用。 之后

await ec.sequelize.sync();

db.belongsTo(db, {
    as: 'db2',
    foreignKey: 'parent_id',
    required: false
});

let rows = await db.findAll({
    where: {
        chk: 0
    },
    include: [{
        model: db,
        as: 'db2',
        attributes: ['id', 'full_name']
    }],
    raw: true,
    limit: 20
}).catch(function (err) {
    console.log(err);
});

【讨论】:

  • 兄弟,谢谢它完美运行,您应该批准自己的问题以获得积分。
猜你喜欢
  • 1970-01-01
  • 2011-05-17
  • 2016-11-13
  • 2013-10-11
  • 2023-03-03
  • 2020-12-07
  • 1970-01-01
  • 2015-06-19
  • 2010-11-20
相关资源
最近更新 更多