首页 文章

在同一个ForeignKey上加入两次

提问于
浏览
0

我正在使用Sequelize进行查询 . 除了一个案例,一切都很顺利 .
我要这个

return db.sequelize.query(`
    SELECT k.name as Name,
    k._id as _id,
    k.notice as notice,
    dv1.value as value1,
    dv2.value as value2,
    dv2._id as v_id
    FROM dict_Keys k
    LEFT JOIN dict_Values dv1 ON k._id=dv1.key_id and dv1.lang_id=` + req.params.id + `
    LEFT JOIN dict_Values dv2 ON k._id=dv2.key_id and dv2.lang_id=` + req.params.id2 + ``, {
      type: Sequelize.QueryTypes.SELECT
    })
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));

在ORM模型中翻译 .

但我无法找到如何在同一个ForeignKey上引用两次 .

包括模型两次的东西是抛出错误,不能包含相同的模型两次 .

声明带有别名的第二个模型然后需要创建相同的外键两次,但命名不同,这是不需要的!

在Sequelize中是否有解决方案,或者目前只有两次声明ForeignKey?

EDIT1:
ForeignKey连接

db.DictKey.hasMany(db.DictValue, {
      foreignKey: 'key_id'
    });

尝试在同一个ForeignKey上包含两次

export function showAll(req, res) {
  return DictKey.findAll({
    include:[{
      model: DictValue,
      where:{
        lang_id: req.params.id
      }
    },
    {
      model: DictValue,
      where:{
        lang_id: req.params.id
      }
    }
  ]
    })
    .then(handleEntityNotFound(res))
    .then(respondWithResult(res))
    .catch(handleError(res));
}

错误在From子句中多次指定了关联名称'dict_Values' .
分配两次

db.DictValue.belongsTo(db.DictKey,{
  as: 'lang1',
  foreignKey: 'key_id'
});
db.DictValue.belongsTo(db.DictKey,{
  as: 'lang2',
  foreignKey: 'key_id'
});

像我这样的东西,我也试过,但不记得确切,但它产生了2个不希望的ForeignKeys .

1 回答

  • 0

    解决方案是为Keys设置别名 .
    我的错是在 belongsTo 协会做 .
    它必须在 hasMany 协会 .

    db.DictKey.hasMany(db.DictValue, {
      foreignKey: 'key_id',
      as : 'value1'
    });
    db.DictValue.belongsTo(db.DictKey,{
      foreignKey : 'key_id',
    });
    db.DictKey.hasMany(db.DictValue, {
      foreignKey: 'key_id',
      as : 'value2'
    });
    db.DictValue.belongsTo(db.DictKey,{
      foreignKey : 'key_id',
    });
    

相关问题