Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

javascript - Sequelize association where one of the models varies

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.


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

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...