1
因此,我有一個屬於用戶的模型Ticket。每個用戶都有很多票。所以user_id是每個Ticket的外鍵。我怎樣才能建立一個查詢,讓我得到每個用戶的用戶名排列的所有票據?我一直在嘗試Ecto:如何從外鍵中的某個字段訂購結果
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
謝謝您的回覆,我已經試過了(或之前類似的東西),但我得到: '[錯誤] #PID <0.3814.0>運行MyApp.Endpoint終止 服務器:localhost:4000( http) 請求:GET/index_by_username **(退出)發生異常: **(Ecto.QueryError)web/controllers/ticket_controller.ex:44:在模型MyApp.Ticket中找不到關聯'用戶'查詢: ' –
'用戶'應該是'用戶' – Gazler
模型中也存在問題。這些協會擁有控制器而不是模型。它現在有效。謝謝! –