Tôi đang vật lộn để tạo một truy vấn với phần tiếp theo.
Một số bối cảnh
Tôi có các mô hình sau:
- A
Manifestation
có thể có [0..n]Event
- An
Event
thuộc về mộtManifestation
(Event
không thể tồn tại mà không có aManifestation
) - A
Place
có thể có [0..n]Event
- An
Event
thuộc về mộtPlace
(Event
không thể tồn tại mà không có aPlace
) - A
Manifestation
có thể có [1..n]Place
- A
Place
có thể có [0..n]Manifestation
Tôi mô hình các mối quan hệ như sau:
Manifestation.hasMany(Event, { onDelete: 'CASCADE', hooks: true })
Event.belongsTo(Manifestation)
Place.hasMany(Event, { onDelete: 'CASCADE', hooks: true })
Event.belongsTo(Place)
Manifestation.belongsToMany(Place, { through: 'manifestation_place' })
Place.belongsToMany(Manifestation, { through: 'manifestation_place' })
Đối với tôi nó có vẻ khá đúng, nhưng đừng ngần ngại nếu bạn có nhận xét.
Câu hỏi
Tôi đang cố gắng truy vấn Place
để có được tất cả Manifestation
và Event
xảy ra trong một nhất định Place
. Nhưng đối với Event
những người, tôi muốn bao gồm họ trong họ Manifestation
ngay cả khi điều Manifestation
đó không xảy ra trong cái đã cho Place
.
Dưới đây là cấu trúc "JSON" mà tôi đang cố gắng đạt được:
{
id: 1,
name: "Place Name",
address: "Place address",
latitude: 47.00000,
longitude: -1.540000,
manifestations: [
{
id: 10,
title: "Manifestation one",
placeId: 1,
events: []
},
{
id: 11,
title: "Manifestation two",
placeId: 3,
events: [
id: 5,
title: "3333",
manifestationId: 11,
placeId: 1
]
}
]
}
Vì vậy, tôi muốn bao gồm Manifestation
với id
: 11, vì một trong số đó Event
xảy ra trong phần đã cho Place
(với id
: 1)
Cập nhật (04/06/20): Hiện tại tôi dựa vào javascript để có được kết quả như mong đợi
Tôi nhận ra rằng nó sẽ tốt đẹp nếu tôi đăng giải pháp hiện tại của mình trước khi hỏi.
router.get('/test', async (req, res) => {
try {
const placesPromise = place.findAll()
const manifestationsPromise = manifestation.findAll({
include: [
{ model: event },
{
model: place,
attributes: ['id'],
},
],
})
const [places, untransformedManifestations] = await Promise.all([
placesPromise,
manifestationsPromise,
])
const manifestations = untransformedManifestations.map(m => {
const values = m.toJSON()
const places = values.places.map(p => p.id)
return { ...values, places }
})
const result = places
.map(p => {
const values = p.toJSON()
const relatedManifestations = manifestations
.filter(m => {
const eventsPlaceId = m.events.map(e => e.placeId)
return (
m.places.includes(values.id) ||
eventsPlaceId.includes(values.id)
)
})
.map(m => {
const filteredEvents = m.events.filter(
e => e.placeId === values.id
)
return { ...m, events: filteredEvents }
})
return { ...values, manifestations: relatedManifestations }
})
.filter(p => p.manifestations.length)
return res.status(200).json(result)
} catch (err) {
console.log(err)
return res.status(500).send()
}
})
Nhưng tôi khá chắc chắn rằng tôi có thể làm điều đó trực tiếp với phần tiếp theo. Bất kỳ ý tưởng hoặc khuyến nghị?
Cảm ơn