Check if model has at least one associated model in Ecto

I’m trying to build a query like this from a list of atoms where every atom represent a table name

i have a log table associated to many tables [:events,:scores,:todos, ...]

the user can input a portion of those tables for filtering (get all logs associated to events or scores or … )

how can i achieve this ?

 widgets = [:expenses, :scores] # this is sanitized as i know the full list of values
 query =
      from(log in Log,
      select: log,
      order_by: [desc: log.updated_at],
      limit: ^limit
 )
 
 # this does not work as i can't do `as: widget` 
 query =
  widgets
  |> Enum.reduce(query, fn widget, query ->
    from(q in query, left_join: w in assoc(q, ^widget), as: widget)
  end)

conditions =
  Enum.reduce(widgets, false, fn widget, query ->
    dynamic([q, [^widget, w]], not is_nil(field(w, :id)) or ^query)
  end)

from(query,
  where: ^conditions
)

You are doing it wrong. Take a look at Named bindings documentation.

Instead of: as: widget you need to use atom i.e.: as: :widget.

widget is a variable that holds the value from widgets (:expenses, :scores)
it seems to me that is not possible to set a named binding with an run_time atom
I thought of setting by binding to the widget name and that to get that name in the conditions variable