Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Let's say I have three models: Bucket Water and Sand. A Bucket can have an association with Water or Sand but not both. So in theory, my relationship definitions would look like this:

Bucket.hasOne(Water, { as: 'contents' })
Water.belongsTo(Bucket)

Bucket.hasOne(Sand, { as: 'contents' })
Sand.belongsTo(Bucket)

This should create a foreign key column on the Water and Sand tables referencing a bucket. And then, in theory, if I query Bucket.getContents() I'll get either the water or the sand object.

Is this legit? I couldn't find any examples of an association like this in the docs. Is there a better way to do it?

Although this is a contrived example, the reason for Water and Sand being different models is they each have a lot of columns that are unique to their model, so it makes sense to keep them separate than try to make one combined model.

question from:https://stackoverflow.com/questions/65600625/sequelize-association-where-one-of-the-models-varies

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
258 views
Welcome To Ask or Share your Answers For Others

1 Answer

Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...