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

Syntax for many-to-many relation getting non-related entities #1855

Open
lenkaiser opened this issue Nov 18, 2024 · 0 comments
Open

Syntax for many-to-many relation getting non-related entities #1855

lenkaiser opened this issue Nov 18, 2024 · 0 comments

Comments

@lenkaiser
Copy link

lenkaiser commented Nov 18, 2024

I've read all the docs, checked the search function for the issues on Github but I can't seem to find a good example for my following use-case. I'm sure this is quite common but I can't get it to work. It's practically equal to (docs) but in my case I want all the users that do not belong to a specific match. The other way around works.
models.ts

export default class MatchModel extends Model {
  static table = "matches";
  static associations = {
    person_matches: { type: "has_many", foreignKey: "match_id" },
  } as const;

  @field("name") name!: string;
  @readonly @date("created_at") createdAt!: number;
}

export default class PersonModel extends Model {
  static table = "persons";
  static associations = {
    persons_matches: { type: "has_many", foreignKey: "person_id" },
  } as const;

  @field("firstname") firstname!: string;
  @field("lastname") lastname!: string;
}

export default class PersonMatchModel extends Model {
  static table = "persons_matches";
  static associations = {
    persons: { type: "belongs_to", key: "person_id" },
    matches: { type: "belongs_to", key: "match_id" },
  } as const;

  @immutableRelation("persons", "person_id") person!: Relation<PersonModel>;
  @immutableRelation("matches", "match_id") match!: Relation<MatchModel>;
}

helper.ts

/// This doesn't work
export const observePersonsNotInMatch = (matchID: string) =>
  database.collections
    .get("persons")
    .query(
      Q.on("persons_matches", "match_id", Q.notEq(matchID)) // Changing this to Q.eq(matchID) returns the persons in the match, so why not vice versa?
    )
    .observe();

/// This works
export const observePersonsNotInMatch = (matchID: string) =>
  database.collections
    .get("persons")
    .query(
      Q.unsafeSqlQuery(
        `SELECT p.*
          FROM persons p
          LEFT JOIN persons_matches pm ON p.id = pm.person_id AND pm.match_id = '${matchID}'
          WHERE pm.match_id IS NULL;`,
      ),
    )
    .observe();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant