例如有三个模型,分类 Category、文章 Article、评论 Comment

分类模型

  • 一个分类有很多文章(hasMany)
class Category extends Model {
  static associate(models) {
    models.Category.hasMany(models.Article)
  }
};

文章模型

  • 每一篇文章都属于一个分类(belongsTo)
  • 一篇文章有很多评论(hasMany)
class Article extends Model {
  static associate(models) {
    models.Article.belongsTo(models.Category)
    models.Article.hasMany(models.Comment)
  }
};

评论模型

  • 每一条评论都属于一篇文章(belongs)
class Comment extends Model {
  static associate(models) {
    models.Comment.belongsTo(models.Article)
  }
};

查询时

一层关联查询

router.get('/', async function (req, res, next) {
    var categories = await models.Article.findAll({
        include: [models.Article],
    })

    res.json(categories);
});

两层关联查询

router.get('/', async function (req, res, next) {
    var categories = await models.Category.findAll({
        include: {
            model: models.Article,
            include: [{
                model: models.Comment,
            }]
        },
    })

    res.json(categories);
});

定义别名

class Category extends Model {
  static associate(models) {
    models.Category.hasMany(models.Article, {as: 'myArticles'})
  }
};

查询时

router.get('/', async function (req, res, next) {
    var categories = await models.Article.findAll({
        include: [{
           model: models.Article,
           as: 'myArticles'
        }],
    })

    res.json(categories);
});

已添加到喜欢了