简体   繁体   English

如何在 KnexJS + bookshelf 中查询嵌套的外键

[英]How to query on nested foreign keys in KnexJS + bookshelf

I use knexJS and bookshelf ORM for my nodejs application.我的 nodejs 应用程序使用 knexJS 和书架 ORM。 The problem is, when a record ID is given, I need to query for getting list of its "great-grandchildren" records.问题是,当给出记录 ID 时,我需要查询以获取其“曾孙”记录的列表。 There are thousands of hundreds records in the destination table, so page number and size are also supposed to pass as params and I need to sort it out via query.目标表中有数千条记录,因此页码和大小也应该作为参数传递,我需要通过查询对其进行排序。 Doing filter after getting all records is not a solution.在获取所有记录后进行过滤不是解决方案。

Let me explain the relationships between models.让我解释一下模型之间的关系。

// MenuItem model
module.exports = (Model, models) => {
  return Model.extend({
    tableName: 'menu_items',
    menu_day() {
      return this.belongsTo(models.MenuDay);
    },
  });
};

This is MenuItem model I am gonna get list for.这是我要获取列表的MenuItem模型。 As you see, it's related to MenuDay model via foreign key.如您所见,它通过外键与MenuDay模型相关。

// MenuDay model
module.exports = (Model, models) => {
  return Model.extend({
    tableName: 'menu_days',
    menu_items() {
      return this.hasMany(models.MenuItem);
    },
    menu() {
      return this.belongsTo(models.Menu);
    }
  });
};

MenuDay model is related to Menu model via foreign key. MenuDay模型通过外键与Menu模型相关联。

// Menu model
module.exports = (Model, models) => {
  return Model.extend({
    tableName: 'menus',
    menu_days() {
      return this.hasMany(models.MenuDay);
    },
    restaurant() {
      return this.belongsTo(models.Restaurant);
    }
  });
};

Menu model is related to Restaurant and a restaurant ID is just given as an input for this position. Menu模型与Restaurant相关, Restaurant ID 仅作为此位置的输入。

// Restaurant model
module.exports = (Model, models) => {
  return Model.extend({
    tableName: 'restaurants',
    menus() {
      return this.hasMany(models.Menu);
    }
  });
};

I tried tremendous solutions for sorting this out but lost a couple of days of mine in this problem.我尝试了很多解决方案来解决这个问题,但在这个问题上失去了几天。 Whatever it is, any help would be highly appreciated!无论是什么,任何帮助将不胜感激! You will save my life.你会救我的命。

You can use the withRelated option of fetch() for that:您可以使用fetch()withRelated选项:

new Restaurant({id: 1}).fetch({
  withRelated: ['menus.menu_days.menu_items']
}).then(restaurant => {
  const menus = restaurant.related('menus')
  const menuDays = menus.related('menu_days')
  const menuItems = menuDays.related('menu_items')
})

I could sort this out myself using Knex only, not Bookshelf.我只能使用 Knex 而不是 Bookshelf 自己解决这个问题。

 knex.raw(` SELECT * FROM menu_items WHERE menu_day_id IN ( SELECT id FROM menu_days WHERE menu_id IN ( SELECT id FROM menus WHERE restaurant_id = ? ) ) LIMIT ? OFFSET ? `, [restaurantId, limit, (page - 1) * limit]) .then(res => { const menuItems = res.rows; });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM