简体   繁体   中英

Problems with sequelize one-to-many associations

I have an existing database that I need to work with.

The user table looks like a bit like this:

id
name
storeId

The store table looks a bit like this:

id
name
address

The user can be associated to just one store. What I want to be able to do is this:

User.hasOne(models.Store, { foreignKey: 'storeId' } ); // Working with existing db, so I need to specify the column name

And then, be able to do something like this:

User.find(1, { include: [models.Store] })

However, just doing this doesn't work. I get the following errors:

Unknown column 'Store.storeId' in 'field list'

It is trying to run this query when I get that error:

SELECT `user`.*, `store`.`id` AS `store.id`, `store`.`name` AS `store.name`, `store`.`storeId` AS `store.storeId` FROM `user` LEFT OUTER JOIN `store` AS `store` ON `user`.`id` = `store`.`storeId` WHERE `user`.`id`=1 LIMIT 1;

Which is obviously wrong. It should be joining on user.storeId = store.id , and it should not being trying to select store.storeId .

I can't figure out how to make this work - any hints?

I am using sequelize v1.7.9

Try this

User.hasOne(models.Store, { foreignKey: 'storeId' , as:'store'})

User.find(1, { include: [{model: models.Store, as: 'store'}] })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM