在自定义模型中定义的字段排序属于许多关联.同时选择几个字段



你在做什么?

我有一个用户模型和一个卡片模型。它们通过自定义表"收藏夹卡"相互关联。现在,我想选择用户favourited的所有卡片,并按createdAt字段对它们进行排序。

models.user.belongsToMany(models.card, { 
through: 'favouriteCards' 
});
models.card.belongsToMany(models.user, {
through: 'favouriteCards',
scope: {
status: 'active'
}
});

我正在编写此代码以获取用户拥有的所有卡:-

this.database.user.findById(userId).then((user: any) => {
user.getCards({
attributes: ['id', 'storyId', 'mediaUri', 'mediaType', 'externalLink']
})
.then((cards: Array<any>) => {
if (cards.length) {
return Promise.resolve(cards);
} else {
throw 'No favourite cards';
}
}).then((cards: Array<any>) => {
return reply({
"cards": cards
});
}).catch((err) => {
console.log(err);
return reply(Boom.notFound("User doesn't have any favourite card"));
});
});

到底发生了什么?

现在,在输出中,我得到了一个关键favouriteCards.我不希望输出中的这个键。另外,我想根据favouriteCardscreatedAt列过滤我的结果。

输出数据杰明

"cards": [
{
"id": 1,
"storyId": 3,
"mediaUri": "http://localhost/api/docs#!/admin/postStory",
"mediaType": "image",
"favouriteCards": {
"createdAt": "2017-08-05T11:45:29.000Z",
"updatedAt": "2017-08-05T11:45:29.000Z",
"cardId": 1,
"userId": 1
}
}
]

尝试包含空数组的选项

例如

this.database.user.findById(userId).then((user: any) => {
user.getCards({
attributes: ['id', 'storyId', 'mediaUri', 'mediaType', 'externalLink'],
include: []
})
.then((cards: Array<any>) => {
if (cards.length) {
return Promise.resolve(cards);
} else {
throw 'No favourite cards';
}
}).then((cards: Array<any>) => {
return reply({
"cards": cards
});
}).catch((err) => {
console.log(err);
return reply(Boom.notFound("User doesn't have any favourite card"));
});
});

最新更新