Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Association creation issuing too many queries... #1404

Closed
j opened this issue Feb 19, 2014 · 3 comments
Closed

Association creation issuing too many queries... #1404

j opened this issue Feb 19, 2014 · 3 comments
Labels
type: feature For issues and PRs. For new features. Never breaking changes.

Comments

@j
Copy link

j commented Feb 19, 2014

var Location = sequelize.define('Location', { /* ... */ });
var LocationHours = sequelize.define('LocationHours', { /* ... */ });

Location.hasMany(LocationHours, { as: 'Hours' });

Location
  .create({ /* ... */ })
  .then(function(location) {
    return location.createHour({ /* ... */ });
  })
  .then(function() {
    /* ... */
  });;

This is issuing an INSERT of Location, then INSERT of LocationHours (with all fields except LocationId), then a SELECT on LocationHours, then an UPDATE on LocationHours (setting LocationId)...

I just want to create the LocationHours with the VenueId since it is known. How can I do this?

Thanks!

@j
Copy link
Author

j commented Feb 19, 2014

It seems oddly dumb to me to create this record first, then update it... I can't find any documentation on doing this. I saw the "create_" methods in the test suite... but everywhere else, this library is doing two creates, then adding... which that in itself is too many queries. I expected the create_ behavior to do two inserts since everything is known for the association creation.

@mickhansen
Copy link
Contributor

createAssociation just uses the internal methods afaik, the reasoning is most likely that the foreign key might be on another table than the specific one you're creating (this is really only a case for belongsTo as i see it - belongsTo also being the reverse of a 1:M hasMany).
If you have the id you need, you can just create the association manually:

LocationHours.create({locationId: location.id})

@mickhansen
Copy link
Contributor

https://github.com/sequelize/sequelize/blob/master/lib/associations/has-many.js#L565
I don't believe this is actually the case anymore. hasMany createAssociations (for 1:M) should now (and for a while) only use a single query.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: feature For issues and PRs. For new features. Never breaking changes.
Projects
None yet
Development

No branches or pull requests

2 participants