Search code examples
elixirphoenix-frameworkecto

Is there a way to update virtual field in the association of a schema?


Can someone help me figure this out?

I have a project that use postgis and I am trying to get associated data.

I have a table that saves agent info and a table to saves areas to each agent. I have a virtual field in the area schema, which I am trying to populate from a DB calculated value

see PhoenixGeo.Agents.get_agent_with_ares!(agent.id)

I'm doing it this way to avoid making two separate queries

I followed practices available online, but it doesn't seem like it's updating the field.

Here is my repo: https://github.com/alt-ctrl-dev/phoenix_geo (edited)

I'm hoping for my end outcome to be:

%Agent{
    id:"agent-id"
    ...
    areas: [
      %Area{
         id: "area-id",
         area: <DB_CALCULATED_VALUE>
         ...
      },
    ...
  ]
}

Any help or direction will be appreciated!

Please and thank you 🙏🏽


Solution

  • I think that

    select_merge: %{
      areas: %{area: fragment("st_area(?) * 1000 * 1000", area.geojson_feature)}
    }
    

    Should go to preload:

    preload: [areas: area, {area: fragment("st_area(?) * 1000 * 1000", area.geojson_feature)}],
    

    I'm typing from my head, you can take a look at examples in the docs and figure out the correct syntax: https://hexdocs.pm/ecto/Ecto.Query.html#preload/3