问题描述
我希望在连接我的多对多关联的连接表上使用排序字段过滤 has_one
。
我有两个架构:
schema "thing1" do
field :name
many_to_many :thing2,Thing2,join_through: "thing1_thing2"
end
schema "thing2" do
field :name
many_to_many :thing1,Thing1,join_through: "thing1_thing2"
end
还有一个看起来像这样的连接表:
schema "thing1_thing2" do
field thing1_id
field thing2_id
field created_date,:utc_datetime
end
我想在 has_one
上添加一个 thing1
,该 created_date
自动按该 schema "thing1" do
...
has_one :oldest_thing2,through: [:created_date,:desc]
end
订购。也许它看起来像这样:
boolean
这样的事情可能吗?我知道过滤关联是但不确定这些过滤器可以做什么。
另一个选项可能是在我可以过滤的关联上有一个 # Dependencies
from sqlalchemy import create_engine
import urllib
# Variables
server = 'My_Server\sqlEXPRESS'
database = 'My_db'
# Connect to sql db
conn_str = (
r'Driver=ODBC Driver 17 for sql Server;'
r'Server=My_Server\sqlEXPRESS;'
r'Database=My_db;'
r'Trusted_Connection=yes;'
)
quoted_conn_str = urllib.parse.quote_plus(conn_str)
engine = create_engine(f'mssql+pyodbc:///?odbc_connect={quoted_conn_str}')
cnxn = engine.connect()
# Load df to sql db
My_df.to_sql(name = 'myTable1',con = cnxn,if_exists = 'append',index = False)
cnxn.close()
字段。看起来像什么?
解决方法
您可以使用过滤的关联,因此您可以执行以下操作:
schema "thing1" do
...
has_one :filtered_thing2,Thing2,where: [flag: true]
end
但我不认为 ecto 对有序关联有任何支持。如果您需要对关联进行排序和过滤的组合,您可以借助可组合查询编写自定义函数。
defmodule Thing1 do
schema "thing1" do
..
has_one :filtered_thing2,where: [flag: true]
end
def custom(query)
from c in query,order_by: [desc: c.created_at]
end
end
然后您可以使用它并查询:
assoc(thing1,:filtered_thing2) |> Thing1.custom() |> Repo.all()