How can i parse Ecto Struct and get the field values

I am getting the below result from an ecto query

My Ecto Query

data = Repo.one(from d in DailyCron, 
  				join: a in Api,
  				on: d.api_id == a.id,
  				join: s in SubCategory,
  				on: d.sub_category_id == s.id,
  				where: d.status == 0, 
  				limit: 1, 
  				select: {d, a, s})

My Ecto Results

{%Ding.Cron.DailyCron{
meta: ecto.Schema.Metadata<:loaded, “daily_cron”>,
api_id: 1,
category_id: 2,
disable: 0,
id: 1,
inserted_at: ~N[2019-08-28 06:23:00],
status: 0,
sub_category_id: 1,
updated_at: ~N[2019-08-28 06:23:00]
},
%Ding.Apis.Api{
meta: ecto.Schema.Metadata<:loaded, “apis_info”>,
api_image_url: nil,
api_name: “YouTube”,
api_url: “https://www.googleapis.com/youtube/v3/”,
content_type: “Video”,
id: 1,
inserted_at: ~N[2019-08-28 15:00:00],
updated_at: ~N[2019-08-28 15:00:00]
},
%Ding.Categorys.SubCategory{
meta: ecto.Schema.Metadata<:loaded, “sub_categories”>,
category_id: 2,
id: 1,
inserted_at: ~N[2019-08-28 04:15:00],
sub_category_name: “cricket”,
updated_at: ~N[2019-08-28 04:15:00]
}}

I want to parse ecto results and get field values. I am a beginner in Elixir. Can someone give me insight on how to achieve this?

I want to get “api_id” and “status” from this %Ding.Cron.DailyCron{
“api_url” from this %Ding.Apis.Api{
id from this %Ding.Categorys.SubCategory{

If you slightly change this to:

{d, a, s}  = Repo.one(from d in DailyCron, .....)

You’ll then find that d, a and s are bound to the values you retrieved. This referred to as pattern matching in Elixir. Your data is returned as a tuple with 3 elements (a 3-tuple). Its formatted that way because thats what you asked for in your select: {d, a, s} keyword.

2 Likes

For now I am using the below query and getting my fields easily. But if anyone know answer for the above please reply.

data = Repo.one(from d in DailyCron, 
  				join: a in Api,
  				on: d.api_id == a.id,
  				join: s in SubCategory,
  				on: d.sub_category_id == s.id,
  				where: d.status == 0, 
  				limit: 1, 
  				select: %{"status": d.status, "api_id": a.id, "sub_cat_id": s.id})

Please specify what fields You expect to retrieve, it’s hard to answer your question with this few information :slight_smile:

1 Like

Have you tried this instead:

{status, aid, sid} = Repo.one(from …, select: {d.status, a.id, s.id})
1 Like

Sorry for that. I have edited my question, mentioning with the fields i want.

Maybe pattern match?

{%{api_id: api_id, status: status}, %{api_url: api_url}, %{id: id}} = ...
1 Like