使用羽毛 - 客户端和续集多对多关系

时间:2018-02-03 21:09:45

标签: feathersjs feathers-sequelize feathers-hook

我正在尝试使用羽毛从n:m关联中获取数据。我正在使用反应为我的前端并使用羽毛 - 客户端和socketio连接到羽毛。

    //connection string where the feathers api is running
const host = 'http://localhost:3030';


const socket = io(host, {
    transports: ['websocket'],
    forceNew: true
});

// construct feathers app
export const client = feathers()
    .configure(hooks())
    .configure(auth({ storage: window.localStorage }))
    .configure(socketio(socket));

但是当我使用myService.find()时,include参数会从hook.params中删除

function (hook) {
        hook.params.sequelize = {
          include: [{ model: hook.app.services.users.Model,
                      as: 'teamOwner'
                      },{
                      model: hook.app.services.users.Model,
                      as: 'Trainer'
                      },{
                      model: hook.app.services.users.Model,
                      as: 'Member'
            }
          ]
        };
      return Promise.resolve(hook);
    }

当我在我之前的钩子中配置它时工作正常,但是每次我们使用的服务都将所有表连接在一起。所以我想在查询中指定要包含哪些表。喜欢这个

client.service('team').find({
                include: [
                { model:client.service('users').Model,
                    as: 'teamOwner'
                },{
                    model:client.service('users').Model,
                    as: 'Trainer'
                },{
                    model:client.service('users').Model,
                    as: 'Member'
                }],
                query: {
                    $sort: {
                        id: 1
                    }
                }
            })

提前致谢

1 个答案:

答案 0 :(得分:1)

由于在客户端和服务器之间只传递params.query,因此最好的方法是创建一个自定义查询参数,指示您要包含的内容:

function (hook) {
  const { $include } = hook.params.query;

  // Remove from the query so that it doesn't get included
  // in the actual database query
  delete hook.params.query.$include;

  const sequelize = {
    include: []
  };

  if(Array.isArray($include)) {
    $include.forEach(name => {
      sequelize.include.push({
        model: hook.app.services.users.Model,
        as: name
      });
    });
  }
  return Promise.resolve(hook);
}

现在,客户端可以在查询中指出他们想要的内容,例如{ query: { $include: [ 'teamOwner', 'Trainer' ] } }