栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

根据关联顺序查找

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

根据关联顺序查找

这是一个有效的示例,说明如何让Sequelize

Books
通过
Author
具有特定姓氏的来获取全部信息。它看起来比实际要复杂得多,因为我正在定义模型,将它们关联,与数据库同步(以创建其表),然后在这些新表中创建虚拟数据。
findAll
在代码中间查找,以明确了解您要执行的操作。

    module.exports = function(sequelize, DataTypes) {    var Author = sequelize.define('Author', {        id: { type: DataTypes.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true        },        firstName: { type: DataTypes.STRING        },        lastName: { type: DataTypes.STRING        }    })    var Book = sequelize.define('Book', {        id: { type: DataTypes.INTEGER, allowNull: false, autoIncrement: true, primaryKey: true        },        title: { type: DataTypes.STRING        }    })    var firstAuthor;    var secondAuthor;    Author.hasMany(Book)    Book.belongsTo(Author)    Author.sync({ force: true })        .then(function() { return Book.sync({ force: true });        })        .then(function() { return Author.create({firstName: 'Test', lastName: 'Testerson'});        })        .then(function(author1) { firstAuthor=author1; return Author.create({firstName: 'The Invisible', lastName: 'Hand'});        })        .then(function(author2) { secondAuthor=author2 return Book.create({AuthorId: firstAuthor.id, title: 'A simple book'});        })        .then(function() { return Book.create({AuthorId: firstAuthor.id, title: 'Another book'});        })        .then(function() { return Book.create({AuthorId: secondAuthor.id, title: 'Some other book'});        })        .then(function() { // This is the part you're after. return Book.findAll({     where: {        'Authors.lastName': 'Testerson'     },     include: [         {model: Author, as: Author.tableName}     ] });        })        .then(function(books) {  console.log('There are ' + books.length + ' books by Test Testerson')        });  }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/409788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号