<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="266450" data-post-id="266450">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="Eiji" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/Eiji/120/36743_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  Eiji
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="dimitarvp" data-post="18" data-topic="51344">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/dimitarvp/48/38664_2.png" class="avatar"> dimitarvp:</div>
<blockquote>
<p>This can probably be made with only one Ecto/SQL query but right now I can’t figure out how (just got up from a nap, lol).</p>
</blockquote>
</aside>
<p>Here you go! <img src="https://forum.elixirforum.com/images/emoji/apple/smiling_imp.png?v=15" title=":smiling_imp:" class="emoji" alt=":smiling_imp:" loading="lazy" width="20" height="20"></p>
<pre data-code-wrap="elixir"><code class="lang-elixir">Mix.install([:ecto_sql, :postgrex])

defmodule Repo do
  use Ecto.Repo, adapter: Ecto.Adapters.Postgres, otp_app: :my_app
end

defmodule Migration do
  use Ecto.Migration

  def change do
    create table("users") do
      add(:name, :string)
      timestamps()
    end

    create table("projects") do
      add(:contributed_by_id, references(:users))
      add(:created_by_id, references(:users))
      add(:name, :string)
      timestamps()
    end
  end
end

defmodule User do
  use Ecto.Schema

  schema "users" do
    field(:name)
    timestamps()
  end
end

defmodule Project do
  use Ecto.Schema

  schema "projects" do
    belongs_to(:contributed_by, User)
    belongs_to(:created_by, User)
    field(:name, :string)
    field(:type, :string, virtual: true)
    timestamps()
  end

  def new(tuple) do
    list = Tuple.to_list(tuple)
    :fields |&gt; __schema__() |&gt; Enum.zip(list) |&gt; then(&amp;struct(__MODULE__, &amp;1))
  end
end

defmodule Example do
  alias Ecto.Query
  require Query

  def cleanup do
    Repo.stop()
  end

  def prepare do
    Application.put_env(:my_app, Repo,
      database: "example",
      # password: "postgres",
      pool_size: 10,
      show_sensitive_data_on_connection_error: true,
      username: System.get_env("USER")
      # username: "postgres"
    )

    Application.ensure_all_started(:ecto_sql)
    Application.ensure_all_started(:ecto_sqlite3)
    Repo.__adapter__().storage_down(Repo.config())
    Repo.__adapter__().storage_up(Repo.config())
    Repo.start_link()
    Ecto.Migrator.up(Repo, 1, Migration)
  end

  def sample do
    %{id: foo_id} = Repo.get_by!(User, name: "Foo")

    Project
    |&gt; Query.from(as: :project)
    |&gt; Query.join(:inner, [project: p], u in User,
      on: u.id == ^foo_id and (u.id == p.contributed_by_id or u.id == p.created_by_id),
      as: :user
    )
    |&gt; Query.select(
      [project: project, user: user],
      {selected_as(
         fragment(
           "case ? when true then ? else ? end",
           project.created_by_id == user.id,
           "created projects",
           "contributed projects"
         ),
         :type
       ), fragment("array_agg(?)", project)}
    )
    |&gt; Query.group_by(selected_as(:type))
    |&gt; Repo.all()
    |&gt; Map.new(fn {key, list} -&gt; {key, Enum.map(list, &amp;Project.new/1)} end)
    |&gt; IO.inspect()
  end

  def seed do
    foo = Repo.insert!(%User{name: "Foo"})
    bar = Repo.insert!(%User{name: "Bar"})
    Repo.insert(%Project{contributed_by: foo, created_by: foo, name: "both"})
    Repo.insert(%Project{contributed_by: bar, created_by: foo, name: "creator"})
    Repo.insert(%Project{contributed_by: foo, created_by: bar, name: "contributor"})
    Repo.insert(%Project{contributed_by: bar, created_by: bar, name: "none"})
  end
end

Example.prepare()
Example.seed()
Example.sample()
Example.cleanup()
</code></pre>
<p>Above code prints:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">%{
  "contributed projects" =&gt; [
    %Project{
      __meta__: #Ecto.Schema.Metadata&lt;:built, "projects"&gt;,
      id: 3,
      contributed_by_id: 1,
      contributed_by: #Ecto.Association.NotLoaded&lt;association :contributed_by is not loaded&gt;,
      created_by_id: 2,
      created_by: #Ecto.Association.NotLoaded&lt;association :created_by is not loaded&gt;,
      name: "contributor",
      type: nil,
      inserted_at: ~N[2022-10-27 16:11:34.000000],
      updated_at: ~N[2022-10-27 16:11:34.000000]
    }
  ],
  "created projects" =&gt; [
    %Project{
      __meta__: #Ecto.Schema.Metadata&lt;:built, "projects"&gt;,
      id: 1,
      contributed_by_id: 1,
      contributed_by: #Ecto.Association.NotLoaded&lt;association :contributed_by is not loaded&gt;,
      created_by_id: 1,
      created_by: #Ecto.Association.NotLoaded&lt;association :created_by is not loaded&gt;,
      name: "both",
      type: nil,
      inserted_at: ~N[2022-10-27 16:11:34.000000],
      updated_at: ~N[2022-10-27 16:11:34.000000]
    },
    %Project{
      __meta__: #Ecto.Schema.Metadata&lt;:built, "projects"&gt;,
      id: 2,
      contributed_by_id: 2,
      contributed_by: #Ecto.Association.NotLoaded&lt;association :contributed_by is not loaded&gt;,
      created_by_id: 1,
      created_by: #Ecto.Association.NotLoaded&lt;association :created_by is not loaded&gt;,
      name: "creator",
      type: nil,
      inserted_at: ~N[2022-10-27 16:11:34.000000],
      updated_at: ~N[2022-10-27 16:11:34.000000]
    }
  ]
}
</code></pre> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="266450" data-batch-url="/posts/batch_likers">
                        3
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/how-to-get-first-x-elements-from-the-list/51344/22">Post #21</a>
	                </div>
	            </div>
              <div id="likers-container-266450" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="266450"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>