Ecto:如何从外键中的某个字段中排序结果

Ecto: How to order results from a certain field in a foreign key

所以我有一个属于用户的模型票证。每个用户都有很多票。所以 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

您在此处使用 preload/3,因为预加载发生在查询之后(它将在其自己的查询中获取所有关联的 ID),因此您无法以这种方式对 user_id 进行排序。

来自文档:

Repo.all from p in Post, preload: [:comments]

The example above will fetch all posts from the database and then do a separate query returning all comments associated to the given posts.

你必须使用 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