creating and using associations

21 views
Skip to first unread message

bob.l...@halton.ca

unread,
May 11, 2015, 9:37:31 AM5/11/15
to sequ...@googlegroups.com, bosko...@hotmail.com
I have a widgets table and an attributes table.  I have the following code

attributes.belongsTo(widgets, {as: 'widgets'}, {foreignKey: 'widgets_id'})
widget.hasMany(attributes, {as: 'attributes'}, {foreignKey: 'widgets_id'})
widget.findAll().then(function(widgets){


how do I now show each widget and its attributes? 

Mick Hansen

unread,
May 11, 2015, 9:40:43 AM5/11/15
to bob.l...@halton.ca, sequ...@googlegroups.com, bosko...@hotmail.com
Prefetching/Includes help you here, (http://sequelize.readthedocs.org/en/latest/docs/models-usage/#eager-loading)

Basically something like:

widget.findAll({
  include: [attributes]
})
--
Mick Hansen
@mhansendev
mhansen.io

bob.l...@halton.ca

unread,
May 11, 2015, 9:45:28 AM5/11/15
to sequ...@googlegroups.com, bob.l...@halton.ca, bosko...@hotmail.com
thank you Mitch. 

once I've done that, i'm not sure how to access widgets[0].attribute[0] or preferably widget['name_of_widget'].attribute['name_of_attribute']

Mick Hansen

unread,
May 11, 2015, 9:54:52 AM5/11/15
to bob.l...@halton.ca, sequ...@googlegroups.com, bosko...@hotmail.com
widgets[0].get('attributes')[0] depending on your naming.
We don't do any kind of pivoting like that, you'll have to do that mapping on your own :)

bob.l...@halton.ca

unread,
May 11, 2015, 10:25:54 AM5/11/15
to sequ...@googlegroups.com, bob.l...@halton.ca, bosko...@hotmail.com
thanks again Mitch,

I have it working now.  if I understand you correctly I have to refer to attributes by their index (the order they are returned) is there any way to return them based on a column 'name'?

Mick Hansen

unread,
May 11, 2015, 10:29:05 AM5/11/15
to bob.l...@halton.ca, sequ...@googlegroups.com, bosko...@hotmail.com
Nope, you'll have to do that sort of mapping on your own :)

bob.l...@halton.ca

unread,
May 11, 2015, 10:59:10 AM5/11/15
to sequ...@googlegroups.com, bob.l...@halton.ca, bosko...@hotmail.com
is there a suggested (standard) way to do this?  do I create a new object and then map to that?  it seems counterintuitive.

Mick Hansen

unread,
May 11, 2015, 11:03:51 AM5/11/15
to bob.l...@halton.ca, sequ...@googlegroups.com, bosko...@hotmail.com
I usually use something like lodash indexBy/groupBy, but i rarely have API's like that.
Reply all
Reply to author
Forward
0 new messages