Composite primary key expressed as tuple, used in Repo.get

I was playing with composite primary keys. I have User and Class schemas, and a join table between them in many_to_many relationship.

The schema of the join table looks like

@primary_key false
  schema "enrollments" do
    belongs_to :user, User, primary_key: true
    belongs_to :class, Class, primary_key: true

Everything works as expected. But is there a way to define the primary key as a tuple {class_id, user_id} that could be used for example in Repo.get(Enrollment, {12, 34}?

Because right now I can only do Repo.all(from e in Enrollment, where: e.class_id == 12 and e.user_id == 34) which is rather lengthy… I could wrap it in a simple function, but just wondering whether I wouldn’t be reinventing the wheel, and it’s already doable by doing something like @primary_key {class_id, user_id}.

Thank you

Not exactly tuple as you want, but by default we should be able to use Repo.get_by/2:

Repo.get_by(Enrollment, class_id: 12, user_id: 34)
1 Like