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


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>I think something like this should work (not tested):</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">from entry in Entry,
  preload: [:tags],
  join: tag in assoc(entry, :tags),
  group_by: entry.id,
  having: fragment("? &lt;@ array_agg(?)", ^tags, tag.name)
</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="27899" data-batch-url="/posts/batch_likers">
                        9
                      </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/help-filtering-many-to-many-associations-with-ecto/4210/12">Post #11</a>
	                </div>
	            </div>
              <div id="likers-container-27899" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="27899"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #11"></div>
  </section>
</div>
    <div class="postbit" id="27934" data-post-id="27934">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="holandes22" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/holandes22/120/11492_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  holandes22
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Your solution worked perfectly as well <a class="mention" href="/u/michalmuskala" rel="nofollow">@michalmuskala</a> but with a much more cleaner query, thank you very much!</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="27934" data-batch-url="/posts/batch_likers">
                        2
                      </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/help-filtering-many-to-many-associations-with-ecto/4210/13">Post #12</a>
	                </div>
	            </div>
              <div id="likers-container-27934" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="27934"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #12"></div>
  </section>
</div>
    <div class="postbit" id="41733" data-post-id="41733">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p><a class="mention" href="/u/overminddl1" rel="nofollow">@OvermindDL1</a> I’m trying to do something similar with a many to many relationship but instead of filtering, I want to calculate the virtual field based on other relationships.</p>
<p>I have many to many relationships of User-Transactions-Merchant, where the user has many Merchants through Transactions and the Merchant has many customers through Transactions. Each Transaction has a value, and the sum of transactions associated between a specific user and a specific merchant is the balance for that users relationship with that merchant.</p>
<p>I use this query to calculate the balance to for user based on the merchant</p>
<pre><code>def customer_balance(user_id: user_id, merchant_id: merchant_id) do
  q = from t in Transaction,
    select: fragment("SUM(CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END)", t.type, t.amount, t.amount),
    where: t.user_id == ^user_id and t.merchant_id == ^merchant_id
  balance = Repo.one(q) || 0
  do_balance(balance, "asset")
   |&gt; Money.new(:USD)
end
</code></pre>
<p>I’ve been trying to do something like this but I haven’t had success.</p>
<pre><code>squery =
  from u in User,
    join: m in assoc(merchant, :merchants),

from sq in subquery(squery),
  select: %{ sq | balance: fragment("SUM(CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END)", t.type, t.amount, t.amount)},
    where: sq.user_id == ^user_id and sq.merchant_id == ^merchant_id
</code></pre>
<p>I think I may may need to preload the transactions prior to the outer query. When I look at just raw SQL nested subqueries, it looks right but I think I’m over thinking it.</p>
<p>In the end I should have a list of users for a specific merchant with the users balance calculated for that merchant. Am I going the right direction here?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="41733" data-batch-url="/posts/batch_likers">
                        0
                      </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/help-filtering-many-to-many-associations-with-ecto/4210/14">Post #13</a>
	                </div>
	            </div>
              <div id="likers-container-41733" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="41733"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #13"></div>
  </section>
</div>
    <div class="postbit" id="41762" data-post-id="41762">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="kickinespresso" data-post="14" data-topic="4210">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/kickinespresso/48/3897_2.png" class="avatar"> kickinespresso:</div>
<blockquote>
<p>I’ve been trying to do something like this but I haven’t had success.</p>
</blockquote>
</aside>
<p>What issues or errors?  Have you tried to formulate your SQL in raw SQL before converting it to Ecto?</p>
<aside class="quote no-group" data-username="kickinespresso" data-post="14" data-topic="4210">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/kickinespresso/48/3897_2.png" class="avatar"> kickinespresso:</div>
<blockquote>
<p>I think I may may need to preload the transactions prior to the outer query. When I look at just raw SQL nested subqueries, it looks right but I think I’m over thinking it.</p>
<p>In the end I should have a list of users for a specific merchant with the users balance calculated for that merchant. Am I going the right direction here?</p>
</blockquote>
</aside>
<p>Looks right on a cursory look so far yep?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="41762" data-batch-url="/posts/batch_likers">
                        0
                      </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/help-filtering-many-to-many-associations-with-ecto/4210/15">Post #14</a>
	                </div>
	            </div>
              <div id="likers-container-41762" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="41762"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #14"></div>
  </section>
</div>
    <div class="postbit" id="44966" data-post-id="44966">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p><a class="mention" href="/u/overminddl1" rel="nofollow">@OvermindDL1</a> -  <a class="mention" href="/u/mbuhot" rel="nofollow">@mbuhot</a> answered my question on <a href="https://stackoverflow.com/questions/45110997/getting-a-virtual-field-in-ecto-calculated-during-a-sql-join-query" rel="noopener nofollow ugc">StackOverflow</a> a few weeks ago. (Thanks <a class="mention" href="/u/mbuhot" rel="nofollow">@mbuhot</a> !!)</p>
<p>Here is the response:</p>
<p>Move the fragment into a macro to keep the code clear:</p>
<pre><code>  defmacro balance_amount(transaction) do
    quote do
      fragment("CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END",
        unquote(transaction).type, unquote(transaction).amount, unquote(transaction).amount)
    end
  end
</code></pre>
<p>Create a subquery with %{user_id, merchant_id, balance}</p>
<pre><code>  def user_merchant_balance do
    from t in Transaction,
    select: %{user_id: t.user_id, merchant_id: t.merchant_id, balance: sum(balance_amount(t))},
    group_by: [t.user_id, t.merchant_id]
  end
</code></pre>
<p>Join to the subquery from the main query, use the map update syntax %{|} to populate the virtual field:</p>
<pre><code>  def merchant_customers(merchant_id) do
    from u in User,
    join: b in subquery(user_merchant_balance()), on: u.id == b.user_id,
    where: b.merchant_id == ^merchant_id,
    select: %{u | balance: b.balance}
  end
</code></pre>
<p>This is the final code I ended up using:</p>
<pre><code>  @doc """
  Retrieves all customers with balances for a merchant
  """
  @spec find_merchant_customers_with_balance(struct) :: [%MyApp.User{}]
  def find_merchant_customers_with_balance(%{"merchant_id" =&gt; id}) do
    q = merchant_customers(id)
    Repo.all(q)
  end

  @doc """
  User balance calcuation macro
  """
  defmacro balance_amount(transaction) do
    quote do
      fragment("CASE WHEN ? = 'debit' THEN (?) ELSE - (?) END",
        unquote(transaction).type, unquote(transaction).amount, unquote(transaction).amount)
    end
  end

  @doc """
  Query for retrieving user balance for merchant
  """
  @spec user_merchant_balance :: %Ecto.Query{}
  def user_merchant_balance do
    from t in Transaction,
    select: %{user_id: t.user_id, merchant_id: t.merchant_id, balance: sum(balance_amount(t))},
    group_by: [t.user_id, t.merchant_id]
  end

  @doc """
  Query for retrieving all the merchants for a customer with abalance
  """
  @spec merchant_customers(number) :: %Ecto.Query{}
  def merchant_customers(merchant_id) do
    from u in User,
    join: b in subquery(user_merchant_balance()), on: u.id == b.user_id,
    where: b.merchant_id == ^merchant_id,
    select: %{u | balance: b.balance}
  end
</code></pre>
<p>I still need to figure out if I can get the <code>balance</code> attribute in the returned query returned as a <code>Money.Ecto</code> struct instead of a raw number. Any ideas on how I might be able to do that?</p>
<p>On the <code>customer_balance</code> function I transform it afterward into <code>Money</code>, but that doesn’t return as a <code>User</code></p>
<pre><code>def customer_balance(user_id: user_id, merchant_id: merchant_id) do
  q = from t in Transaction,
    select: fragment("SUM(CASE WHEN ? = 'credit' THEN (?) ELSE - (?) END)", t.type, t.amount, t.amount),
    where: t.user_id == ^user_id and t.merchant_id == ^merchant_id
  balance = Repo.one(q) || 0
  do_balance(balance, "asset")
   |&gt; Money.new(:USD)
end
</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="44966" data-batch-url="/posts/batch_likers">
                        2
                      </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/help-filtering-many-to-many-associations-with-ecto/4210/16">Post #15</a>
	                </div>
	            </div>
              <div id="likers-container-44966" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="44966"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #15"></div>
  </section>
</div>
    <div class="postbit" id="45398" data-post-id="45398">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Looks like you can populate a virtual field with a custom type in ecto 2.2:</p>
<p>Edit: Not quite, can’t use <code>type</code> and <code>sum</code> together, but another layer of <code>subquery</code> does the trick:</p>
<pre><code>@spec user_merchant_balance :: %Ecto.Query{}
def user_merchant_balance do
  from record in subquery(
    from t in Transaction,
    select: %{user_id: t.user_id, merchant_id: t.merchant_id, balance: sum(balance_amount(t)},
    group_by: [t.user_id, t.merchant_id])
  select: %{user_id: record.user_id, merchant_id: record.merchant_id, balance: type(record.balance, Money.Ecto.Type)}
end
</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="45398" data-batch-url="/posts/batch_likers">
                        0
                      </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/help-filtering-many-to-many-associations-with-ecto/4210/17">Post #16</a>
	                </div>
	            </div>
              <div id="likers-container-45398" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="45398"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #16"></div>
  </section>
</div>
    <div class="postbit" id="352110" data-post-id="352110">
  <section>
    <div class="post-wrap">


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

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>This conversation was a top result in Google with “Ecto many to many relationship filtering”.</p>
<p>I tested performance a bit today in many to many case where I have apartments table, amenities table and then join table between them.</p>
<p>using <code>array_agg()</code> was 10x slower than doing:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">SELECT a.*
FROM apartments a
JOIN apartment_amenities aa ON a.id = aa.apartment_id
JOIN amenities am ON aa.amenity_id = am.id
WHERE a.city = 'Chicago'
  AND am.name IN ('fridge', 'gym')
GROUP BY a.id
HAVING COUNT(DISTINCT am.name) = 2;
</code></pre>
<p>Or:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">SELECT a.*
FROM apartments a
JOIN apartment_amenities aa1 ON a.id = aa1.apartment_id
JOIN amenities am1 ON aa1.amenity_id = am1.id
JOIN apartment_amenities aa2 ON a.id = aa2.apartment_id
JOIN amenities am2 ON aa2.amenity_id = am2.id
WHERE a.city = 'Chicago'
  AND am1.name = 'fridge'
  AND am2.name = 'gym';
</code></pre>
<p>I don’t yet know how to turn this into Ecto but I would highly advice anyone from using a virtual <code>array_agg</code> aggregation because Postgres can’t use any indexes properly with that.</p>
<p>Hope this is useful for others too <img src="https://forum.elixirforum.com/images/emoji/apple/bowing_man.png?v=15" title=":bowing_man:" class="emoji" alt=":bowing_man:" loading="lazy" width="20" height="20"></p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="352110" data-batch-url="/posts/batch_likers">
                        0
                      </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/help-filtering-many-to-many-associations-with-ecto/4210/18">Post #17</a>
	                </div>
	            </div>
              <div id="likers-container-352110" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="352110"
                     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>