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

hasOne does not work if there are two foreign keys to the same model #339

Open
Feelzor opened this issue Apr 27, 2022 · 0 comments · May be fixed by #341
Open

hasOne does not work if there are two foreign keys to the same model #339

Feelzor opened this issue Apr 27, 2022 · 0 comments · May be fixed by #341

Comments

@Feelzor
Copy link

Feelzor commented Apr 27, 2022

When trying to create two foreign keys to the same model, using the function hasOne can only retrieve the first of the two referenced objects.

Say for example you have a User, and the possibility to report a user with Report like so:

class User extends Model {
  static table = 'users';

  static fields = {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },

    name: DataTypes.string(30)
  };
}

class Report extends Model {
  static table = 'reports';
  static timestamps = true;

  static fields = {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
    },
  };

  static user(): Promise<Model | Model[]> {
    return this.hasOne(User);
  }
}
Relationships.belongsTo(Report, User, { foreignKey: 'reportedUserId' });
Relationships.belongsTo(Report, User, { foreignKey: 'reporterUserId' });

A call to Report.where('id', 1).user() will only return the first one (the reported user) and not the second one.
And using hasMany doesn't work, since we have two oneToMany relationships.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
1 participant