【问题标题】:sequelizejs eager fetch many to manysequelizejs 渴望获取多对多
【发布时间】:2017-04-02 02:10:01
【问题描述】:

我正在尝试使用 Sequelizejs v3 在 Nodejs 中的连接表上获取渴望。

所以,1个Tag可以属于Many Images,Many Images可以有多个Tag。

标签 1 - > M ImageTag M

当我尝试执行查询时收到Unhandled rejection Error: Tag is not associated to ImageDetails。

function getImagesFromAlbum(albumid, callback, errCallback){
  ImageDetails.findAll({where: { AlbumId: albumid }, include: [{model: Tag}]}).then((data) => {
    return callback(data)
  }).catch((err) => {
    return errCallback(err)
  })
}

预期的返回结果应该是根据专辑的数据,以及该图像的关联标签

这里是加入的关系

ImageDetails.belongsToMany(Tag, { as: { singular: "tag", plural: "tags" }, through: { model: ImageTag, unique: false }, foreignKey: "ImageId"})
Tag.belongsToMany(ImageDetails, { as: { singular: "image", plural: "images" }, through: { model: ImageTag, unique: false },  foreignKey: "TagId"})

这里是模型设计

标签模型

const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  name: {
    type: Sequelize.STRING
  }
}

const name = "Tag"

ImageTag 模型(连接表)

const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  }
}
const name = "ImageTag"

ImageDetails 模型

import { Sequelize, db } from "../config/MySqlConfiguration"

const model = {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    primaryKey: true
  },
  ImageLocation: {
    type: Sequelize.STRING
  },
  originalName: {
    type: Sequelize.STRING
  }
}

const name = "ImageDetails"

*注意 sequelize.define 是故意省略的。

【问题讨论】:

    标签: mysql node.js sequelize.js


    【解决方案1】:

    在 belongsToMany 中使用别名 (as) 定义模型之间的关系时,您需要记住在预先加载模型时包含此别名,因此您的查询将如下所示

    ImageDetails.findAll({
        where: { AlbumId: albumid },
        include: [{ model: Tag, as: 'tags' }]
    }).then((data) => {
        return callback(data)
    }).catch((err) => {
        return errCallback(err)
    });
    

    您要查询的AlbumId 是什么?根据您的模型定义,ImageDetails 模型没有这样的字段。

    【讨论】:

      猜你喜欢
      • 2016-01-10
      • 2014-11-29
      • 2021-06-04
      • 2014-12-15
      • 2014-05-15
      • 2017-06-06
      • 1970-01-01
      • 2016-02-24
      • 2015-05-16
      相关资源
      最近更新 更多