freewebwithme

freewebwithme

How to use correctly result from Repo.query()

My data model is like this

Category has_many Products
Products belongs_to Category
Products belongs_to User

What I want from database query is this.
All categories and 10 products for each category and also each user who owns the product.

I post a question here. searched forum.
But couldn’t find a solution for this.
So I ended up using raw sql to get what I want.

here is sql query.

SELECT *
  FROM categories c LEFT JOIN LATERAL
          (SELECT p.*
           FROM products p
           WHERE c.id = p.category_id
           ORDER BY p.updated_at
           LIMIT 10) AS p
           ON 1 = 1
           INNER JOIN users ON p.user_id = users.id

query = "SELECT * FROM categories c LEFT JOIN LATERAL (SELECT p.* FROM products p WHERE c.id = p.category_id ORDER BY p.updated_at LIMIT 10) AS p ON 1=1 INNER JOIN users u ON p.user_id = u.id"

{:ok, result} = Repo.query(query)

And finally I got correct query result from that raw query.
But rows and columns in result, all columns and rows are in single list.
for exmaple,

%Postgrex.Result{
  columns: ["id", "name", "id", "product_name"...etc.],
  rows: [
    [1, "Electronics", "2", "TV",,,,, etc]
    [2, "Software", .....],
    [3, ""....]
  ]
}

All join table’s rows and columns are in same list.

So I need to use Enum.slice to get cols and rows for each schema(Category, Product, User)
for example,

category_cols = Enum.slice(query_result.columns, 0, 4)                                                                                                                                                                                        
category_rows = Enum.map(query_result.rows, &Enum.slice(&1, 0, 4))
 # Build categories
categories = Enum.map(category_rows, &Repo.load(Category, {category_cols, &1})

I have to do this for Product and User. And I need to connect association for each struct manually
Something like this

Enum.map(categories, &Map.put(&1, :products, product))

And I think it is tedious and error prone solution.

So my questions are

  1. Is there any way to convert my raw query to ecto query? So I can get a ready to use struct format.
  2. Is it better to define new absinthe schema object type like :top10_products and define new field same as raw query result?

Most Liked

benwilson512

benwilson512

Author of Craft GraphQL APIs in Elixir with Absinthe

Ecto.Repo — Ecto v3.14.0 is a super handy function for turning query results into ecto structs.

Where Next?

Popular in Questions Top

_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
Kurisu
For example for a current url like http://localhost:4000/cosmetic/products?_utf8=✓&query=perfume&page=2, I would like to get: ...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
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
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers’ Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
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
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
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New

Other popular topics Top

sen
Hi All, I set a environment variables in dev.exs , like below code. when i start server, how can i set the ${enable} value? thanks. d...
New
danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29603 241
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
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
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
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
KronicDeth
Elixir plugin for JetBrain’s IntelliJ Platform (including Rubymine) This is a plugin that adds support for Elixir to JetBrains IntelliJ...
289 36352 110
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 48342 226
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New

Latest on Elixir Forum

Elixir Forum

We're in Beta

About us Mission Statement