kentor kentor - 1 year ago 49
Node.js Question

Output associated information from two tables in sequelize

Assuming I have two tables:

. One TradePrice may be used by multiple TradeSettings. In Express I want to list all TradeSettings with the according TradePrice and thus I use sequelize's
for both tables and pass the results to my jade view.

My problem:

How can I output the right price for the according TradeSetting without creating a new select for every iteration of my jade view:

each tradeSetting in tradeSettings
td #{tradeSetting.Name}
td #{tradeSetting.PriceId}
td // the according price for this tradeSetting

I thought about using something like an associative array so that I could output it with
but I am not sure if this is possible and what I would need to do?

My two tables look like this (simplified):

TradeSettings (Id, Name, PriceId)

TradePrices (Id, Price)

Side note: I am not using foreign keys in my database yet, but I could add them there and adapt the models accordingly if necessary.

Answer Source

Preprocess your data by iterating over your TradeSettings, find the matching TradePrice for each TradeSetting and save it as a new property into every TradeSetting.

After that every TradeSetting has its correct TradePrice easily accessible as a property (just like you would access Name or PriceId).

Then you can then easily iterate over your TradeSettings and in your third td line (from your example) you can use #{tradeSetting.TradePrice.Price}

edit: You mentioned you're using sequelize, if its possible to set foreign keys in your db then you could make use of that as well. If everything is set correctly try

TradeSetting.findAll({ include: [TradePrice])

then in your jade template