Preload queries for has many relationship

I am currently trying to query all Accounts in my database that belong to the email and owner_id being passed in. The Account has many account opportunities. I’m wondering if it is possible to preload certain account opportunities given they are not closed, and that the account does in fact have many account opportunities(the collection is not empty or nil).

I have this so far. I’d like to be able to do something like this as well as include all accounts where account_opportunities (the has_many) is not empty.

def get_account_by_email(email, owner_id),
    do:
      Repo.all(Account, account_owner_email: email, owner_id: owner_id)
      |> Repo.preload(account_opportunities: from(ac in AccountOpportunity, where: ac.closed == false))

I think this should do it:

  from(a in Account,
    join: ao in assoc(a, :account_opportunities),
    where: a.account_owner_email == ^email and a.owner_id == ^owner_id and ao.closed == false,
    preload: [account_opportunities: ao]
  )
  |> Repo.all()
1 Like