5

我一直在通过 sequelize 在 postgres db 上使用 feathersjs/nodejs。在我的数据库中,我有用户表和事件表。它们有两倍的关系:

events.belongsTo(models.users, {
  foreignKey: {
    name: 'creatorId',
    allowNull: false
  },
  onDelete: 'CASCADE',
  as: 'creator'
});

events.belongsToMany(models.users, {
  through: 'event_participants',
  as: 'participants',
  foreignKey: 'eventId',
  otherKey: 'userId'
});
models.users.belongsToMany(events, {
  through: 'event_participants',
  as: 'events'
});

一切正常,创建了表格,并包括让用户作为参与者参与活动。问题是通过关联查询。我正在尝试为当前用户获取事件,所以我需要创建者是当前用户的事件和参与者之一是当前用户的事件。问题是第二部分“查询当前用户是参与者之一的位置”。我期待这样的事情

'api/events?$or[0][creatorId]=currUserId&$or[1][participants][$contains]=currUserId'

但它不起作用,因为没有包含“参与者”这样的列,所以我无法查询它。所以现在我只是获取所有事件并在后挂钩中为当前用户过滤它们,但这似乎是错误的。这样做的正确方法是什么?

是的,我知道我可以通过将用户包含在用户中并获取他来获取用户是参与者之一的事件,但问题是我无法将这些数据全部排序,它被单独排序,另一个问题是在前端进行分页。

4

2 回答 2

3

查询嵌套关联不是 Feathers 通用查询语法的一部分。在 Sequelize 的情况下,应根据您的需要使用params.sequelize组装查询,并包括如feathers-sequelize 关联文档中所示:

    // GET /my-service?name=John&include=1
    function (context) {
       if (context.params.query.include) {
          const AssociatedModel = context.app.services.fooservice.Model;
          context.params.sequelize = {
             include: [{
               model: AssociatedModel
               // normal Sequelize where query here
              }]
          };
          // delete any special query params so they are not used
          // in the WHERE clause in the db query.
          delete context.params.query.include;
       }

       return Promise.resolve(context);
    }
于 2018-08-01T01:12:46.713 回答
1

在@daff 的回答的帮助下,我找到了这样的解决方案......我得到的错误可以在这里找到。

const { authenticate } = require('@feathersjs/authentication').hooks;

function includeBefore(hook) {
  currUserId = hook.params.user.id;
  userModel = hook.app.services.users.Model
  hook.params.sequelize = {
    where: {
      $or: [
        {
          creatorId: currUserId
        },
        {
          '$participants.id$': currUserId  //no idea what are '$$' for but it made it work
        }
      ]
    },
    include: [
      {
        model: userModel,
        as: 'creator',
      }, {
        model: userModel,
        as: 'participants',
        duplicating: false //fixed error that I was getting 
      }
    ],
  }
  return hook;
}


module.exports = {
  before: {
    all: [
      authenticate('jwt'),
      hook => includeBefore(hook)
    ],
.........
于 2018-11-10T00:53:23.553 回答