LawJolla

LawJolla

Selecting Fields From a many_to_many Link Table

I’ve looked for the duplicate answer. If I’ve missed it, please link it so I can delete this question.

In the Ecto docs many_to_many example, what’s the best way to get the timestamps returned from users_organizations when following the post/tags query example? e.g.

# Get all users for a given organization
organization = Repo.get(Organization, 1)
users = Repo.all(assoc(organization, :users))
# How to get timestamps from users_organization (when user joined organization)?

Marked As Solved

lukerollans

lukerollans

I think this is a great example of where join schemas shine. Assuming you have a schema defined as such…

defmodule YourApp.UserOrganization do
  use Ecto.Schema

  schema "users_organizations" do
    belongs_to :organization, YourApp.Organization
    belongs_to :user, YourApp.User

    timestamps()
   end

   ....
end

You could run a query like so

organization_id = 1

YourApp.UserOrganization
|> where([uo], uo.organization_id == ^organization_id)
|> preload(:user)
|> Repo.all

Disclaimer: I prefer the pipeline syntax for Ecto queries, feel free to switch over to from if you like :stuck_out_tongue:

Now, you have a list of UserOrganization structs which include the timestamps of when the user joined the organization. If you need to access the user itself, just use the assoc (which was preloaded above for demonstration).

Also Liked

lukerollans

lukerollans

Outside of naming each field in a select statement, is there a way to unnest the structs so it’s all at the same level, e.g.

Nope, by definition structs can only contain fields they’re defined with. It’s impossible for %UserOrganization.email to be a thing, unless you actually add it to the schema.

Glad it helped, though! Remember to mark it as solved so others can get help, too :slight_smile:

LawJolla

LawJolla

Thank you, it works perfectly!

I had tunnel vision. I thought that I had to start with Organization… because that’s the id I had. Query UserOrganization with the organization_id… duh. I’m very comfortable in SQL, so in many to many, I always think to search a table, join the link table, then join the other table.

Quick tangential question… your query returns a list of structs. Inside the structs are nested structs keyed by the schema name, e.g.

[
 
 %UserOrganization{
     inserted_at:...
    user: %User{
      email: "email"
      ...
    }
 }
]

Outside of naming each field in a select statement, is there a way to unnest the structs so it’s all at the same level, e.g.

[
  %UserOrganization{
     inserted_at: ...
     email: "email",
    ...
  }
]

Thank you again. Huge help.

Where Next?

Popular in Questions Top

electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
JulienCorb
I am trying to implement my new.html.eex file to create new posts on my website. new.html.eex: <h1>Create Post</h1> <%= ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
jerry
Good day to you all. I have been struggling to get a query involving like and ilike to work. Can anyone assist me on this, please? pro...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New

Other popular topics Top

rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list. ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
nobody
Hi! In PHP: $_SERVER[‘SERVER_ADDR’] - in Elixir? Searched the docs for ip address and the web, no good results. Thanks!
New
jaysoifer
Is there a way to rollback a specific migration and only that one (“skipping” all the other ones)? Would mix ecto.rollback -v 200809061...
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
jason.o
In the code below, if the create action is not set to accept “extra_key” as an input, it errors out with a message shown above. Is there ...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement