shahryarjb

shahryarjb

How to get struct in array

Hello, how do I get struct in array ? please see my pic :

I need to get the struct’s params , like this : a.cms_post.title

My output is :

[
  %TrangellCmsService.Cms.Db.Post{
    __meta__: #Ecto.Schema.Metadata<:loaded, "cms_post">,
    changelog: true,
    changelog_category: "/ss/ppos",
    cms_post_category: #Ecto.Association.NotLoaded<association :cms_post_category is not loaded>,
    cms_post_category_id: "960c30f2-183e-4430-a96d-4f0fd41fe37b",
    description: "test test test test test test tetststststss tskkkstest of test fo test of test more test more test for test for test tes",
    discourse: true,
    discourse_link: "/ss/ppos",
    download_ext_link: "/ss/ppos", 
    group_acl: "admin",
    id: 6,
    inserted_at: ~N[2018-04-29 11:45:05.311436],
    learn: true,
    learn_category: "/ss/ppos",
    pic_x1_link: "/ss/ppos",
    pic_x2_link: "/ss/ppos",
    pic_x3_link: "/ss/ppos",
    plugin: true,
    plugin_category: "/ss/ppos",
    post_type: "free",
    price: "30000",
    screen_shot: false,
    screen_shot_category: "/ss/ppos",
    seo_alias_link: "7seo-why-seo",
    seo_description: "for the test for test for test for test tete of test",
    seo_language: "fa",
    seo_language_link: "/ss/ppos",
    seo_tag: "test,test,test,test",
    seo_words: "test,test,test,test",
    status: true,
    title: "shahryar",
    updated_at: ~N[2018-04-29 11:45:05.311884]
  }
]

Marked As Solved

Eiji

Eiji

@shahryarjb: I assumed you want to fetch online titles. If so then easier is to call specific query.

defmodule Example do
  import Ecto.Query

  # aliases for Post and PostCategory here

  def sample(seo_alias_link, group_acl) do
    query =
      from(
        post_category in PostCategory,
        join: post in assoc(post_category, :cms_post)
        order_by: post_category.inserted_at,
        limit: 10,
        preload: [cms_post: post],
        where: p.seo_alias_link == ^seo_alias_link
      )

    if group_acl == "admin" do
      query
    else
      where(
        query,
        [post_category, post],
        post_category.group_acl == ^group_acl and post.group_acl == ^group_acl
      )
    end

    query
    |> Repo.all()
    |> Enum.map(& &1.cms_post)
    |> List.flatten()
    |> Enum.map(& &1.title)
  end
end

Example.sample("jsjsjs", "admin")

Also Liked

peerreynders

peerreynders

Something like

Enum.map(a.cms_post, &(Map.get(&1,:title)))

would return a list of title values

Map.get/3
Enum.map/2

a.cms_post
|> hd()
|> Map.get(:title)

returns the title of the post in the head of the list

Kernel.hd/1

def get_title([%TrangellCmsService.Cms.Db.Post{title: title}|_]),
  do: title

i.e. using pattern matching for destructuring rather than dot notation.

NobbZ

NobbZ

Not array, it is a linked list, and you can use the usual iteration functions from the Enum module.

You can not directly acces the fields because it’s ambiguous which of the potentially many lists contents you want to access.

Eiji

Eiji

@shahryarjb If I understand you correctly then this code should help you:

categories # here you have root list from your gist
|> Enum.find(& &1.seo_alias_link == "jsjsjs") # here you have list element
|> Map.fetch!(:cms_post) # here you are fetching sub-list from element
|> Enum.map(& &1.title) # finally here you are getting title for all elements
Eiji

Eiji

@shahryarjb: Sorry, but I don’t know few things:

  1. What’s value of category_alias variable - "jsjsjs" ?
  2. What’s value of group_acl variable - root list from gist ?
  3. fetch_posts_by_category_alias function body

If I assumed correctly (about your variables) then:

def load_posts_by_category_alias(category_alias, group_acl) do
  group_acl
  |> Enum.find(& &1.seo_alias_link == category_alias)
  |> Map.fetch!(:cms_post)
  |> Enum.map(& &1.title)
end
Eiji

Eiji

@shahryarjb: Then it’s really simple. Assuming you want only list of titles:

defmodule Example do
  import Ecto.Query

  # aliases for Post and PostCategory here

  def sample(seo_alias_link, group_acl) do
    query =
      from(
        post_category in PostCategory,
        inner_join: post in assoc(post_category, :cms_post),
        order_by: post_category.inserted_at,
        limit: 10,
        select: post.title,
        where: p.seo_alias_link == ^seo_alias_link
      )

    if group_acl == "admin" do
      query
    else
      where(
        query,
        [post_category, post],
        post_category.group_acl == ^group_acl and post.group_acl == ^group_acl
      )
    end
  end
end

"jsjsjs" |> Example.sample("admin") |> Repo.all

Where Next?

Popular in Questions Top

shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
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
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
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
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New

Other popular topics Top

JakeBecker
TL;DR: I’ve just released an implementation of Microsoft’s IDE-independent Language Server Protocol for Elixir. It adds language support ...
1140 51847 244
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
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

We're in Beta

About us Mission Statement