Как указать attributes вложенной ассоциации в Sequelize
У меня есть 4 сущности.
- Библиотека
- Книга
- Автор
- Профиль автора
Мне нужно получить список всех книг, в нужной библиотеке и вернуть еще инфу об авторе. Пример:
Book.findAll({
where: {library: 1},
attributes: [
'id',
'name',
],
include: [
{
model: db.User,
as: 'author',
foreignKey: 'authorId',
include: [{
model: db.UserProfile,
as: 'profile',
foreignKey: 'userId',
attributes: ['name']
}],
attributes: [
'id',
'email'
],
raw: true
}
],
}).then((result) => {
console.log(result)
}).catch((err) => {
console.error(err)
})
Это вернет мне:
[
{
"id": 3,
"name": "book name",
"author": {
"id": 1,
"username": "author_username",
"profile": {
"name": "Author Real Name"
}
}
}
]
Вроде все ок, но я хочу чтобы у меня в объекте author
не-было ключа profile
, а просто выводилось name
.
Я делаю что-то вроде:
Book.findAll({
where: {library: 1},
attributes: [
'id',
'name',
],
include: [
{
model: db.User,
as: 'author',
foreignKey: 'authorId',
include: [{
model: db.UserProfile,
as: 'profile',
foreignKey: 'userId',
attributes: []
}],
attributes: [
'id',
'email'
[Sequelize.col('profile.name'), 'name']
],
raw: true
}
],
}).then((result) => {
console.log(result)
}).catch((err) => {
console.error(err)
})
На что получаю вроде логичную ошибку.
sqlMessage: "Unknown column 'author.profile.name' in 'field list'",
Собственно вопрос - как это победить?)
Источник: Stack Overflow на русском