Skip to content

Inconsistent create behavior when starting from hasMany vs belongsTo #8716

Closed

Description

@geoffreak

Running version 4.23.2

Say I have two models, Parent and Child and an instance of each parent and child respectively. Parent hasMany Child and Child belongsTo Parent.

Why is it that the association create behavior is different when creating the other? I expected the new instance returned from each create call.

createChildResult = await parent.createChild()
// createChildResult is a new Child instance ✅

createParentResult = await child.createParent()
// createParentResult is the same child??? ❌
createParentResult === child // Why is this true???

The docs don't seem to cover this backwards behavior either. The return type is just listed as Promise with no types.

Activity

  1. stale commented on Feb 27, 2018

    @stale

    This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. If this is still an issue, just leave a comment 🙂

  2. geoffreak commented on Feb 28, 2018

    @geoffreak
    Author

    As far as I'm aware, this is still an issue.

  3. sushantdhiman commented on Mar 1, 2018

    @sushantdhiman
    Contributor

    Hmm, looks like it does return same child model;s instance

    'use strict';
    
    const Sequelize = require('./index');
    const sequelize = require('./test/support').createSequelizeInstance({
      logging: console.log
    });
    
    const Course = sequelize.define('course', {
      name: Sequelize.STRING,
    });
    
    const Question = sequelize.define('question', {
      name: Sequelize.STRING,
    });
    
    Course.hasMany(Question);
    Question.belongsTo(Course);
    
    sequelize.sync({ force: true })
      .then(() => {
        return Sequelize.Promise.join(
          Course.create({ name: 'c' }),
          Question.create({ name: 'q' })
        );
      })
      .spread((c, q) => {
        return Sequelize.Promise.join(
          c.createQuestion({ name: 'q1' }),
          q.createCourse({ name: 'c1' })
        );
      }).spread((c, q) => {
        console.log(c.constructor.name, q.constructor.name);
      });
    question question
  4. added
    type: bug
    on Mar 1, 2018
  5. Munter commented on Oct 2, 2018

    @Munter
    Contributor

    I just ran into the same issue. The behavior is quite surprising

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    type: bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions