使用feathers-client并化多对多关系 [英] Using feathers-client and sequelize many-to-many relation
问题描述
我正在尝试使用羽毛从n:m关联中获取数据.我在前端使用React,并使用feathers-client和socketio连接到羽毛.
I'm trying to get data from an n:m association using feathers. I'm using react for my front-end and connecting to feathers using the feathers-client and 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()时,包含参数将从hook.params中删除
But when I use the myService.find() the include param gets removed from the 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);
}
当我在before挂钩中对其进行配置时,它可以正常工作,但是每次使用该服务时,所有表都将连接在一起.因此,我想在查询中指定要包括的表.像这样
When I configure it in my before hook it works fine, but then every time the service us used all the tables are joined together. So I want to specify in the query which tables to include. Like this
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
}
}
})
预先感谢
推荐答案
由于只有params.query
在客户端和服务器之间传递,因此最好的方法通常是创建一个自定义查询参数,以指示要包含的内容:
Since only params.query
is passed between the client and the server the best way is usually to create a custom query parameter that indicates what you want to include:
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' ] } }
Now the client can indicate what they want in the query, e.g. { query: { $include: [ 'teamOwner', 'Trainer' ] } }
这篇关于使用feathers-client并化多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!