eveningkid / denodb

MySQL, SQLite, MariaDB, PostgreSQL and MongoDB ORM for Deno

Home Page:https://eveningkid.com/denodb-docs

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

Feelzor opened this issue · comments

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.