所以我有一个属于用户的模型Ticket。每个用户都有很多票。因此user_id是每个Ticket的外键。如何构建一个查询,以获取每个用户的用户名所订购的所有票证?我一直在尝试
query = from u in User,
preload: [:tickets]
query_tickets = from t in Ticket,
order_by: u.username,
preload: [users: ^query]
tickets = Repo.all(query_tickets)
但它说模型Ticket没有任何用户关联?
schema "tickets" do
field :subject, :string
field :body, :string
field :followup, :boolean
field :closed, :boolean
field :file, :string
field :filepath, :map
belongs_to :user, UserController
has_many :ticket_message, TicketMessageController
timestamps
end
schema "users" do
field :name, :string
field :username, :string
field :password, :string, virtual: true
field :password_hash, :string
field :email, :string
field :client, :string
field :role, :integer
has_one :services, ServiceController
has_many :tickets, TicketController
timestamps
end
答案 0 :(得分:5)
您在这里使用preload/3,因为预加载发生在查询之后(它将在其自己的查询中获取所有关联的ID),您无法以这种方式对user_id进行排序。
来自文档:
Repo.all from p in Post, preload: [:comments]
上面的示例将从数据库中获取所有帖子,然后执行单独的查询,返回与给定帖子关联的所有评论。
您必须使用join/5
query_tickets = from t in Ticket,
join: u in assoc(t, :user)
order_by: u.username,
tickets = Repo.all(query_tickets)
如果您希望在故障单的user
键上设置用户(就像预加载一样),那么您可能需要查看https://github.com/elixir-lang/ecto/issues/962