2017-04-01 50 views
0

我想获取与Sequelizejs v3的Nodejs连接表上渴望。sequelizejs渴望获取许多到很多

所以,1个标签可以属于许多图像,并且许多图像可以有多个标签。

标签1 - > MS ImageTag中号< - 1图片

我得到Unhandled rejection Error: Tag is not associated to ImageDetails当我试图EXCUTE查询。

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

的预期收益结果应根据ALBUMID是数据,与该图像的assiociate标签

这里是加入

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特意省略。

回答

0

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

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

什么是你想要执行查询的​​?根据你的模型定义,ImageDetails模型没有这样的领域。