如何从Ecto中的关联中选择特定字段?

时间:2015-10-19 15:42:36

标签: elixir ecto

我有以下型号

schema "products" do
  field :quantity, :integer
  field :price,    :float
  field :discount, :float, default: 0.0

  belongs_to :order, Order
end

schema "orders" do
  field :received_at,   Ecto.Date
  field :shipment_cost, :float
  field :savings,       :float
  field :shop_name,     :string

  has_many :products, Product
end

我现在要做的是获取包含特定字段的订单:savingsshipment_cost

我还需要针对该订单生成相关产品,但同样需要仅包含特定字段:quantitypricediscount

如何以最有效的方式做到这一点?

def for_amount(order_id) do
  products_query = from product in Product,
                     select: %{
                       order_id: product.order_id,
                       quantity: product.quantity,
                       price:    product.price,
                       discount: product.discount
                     }

  from order in Order,
    preload: [products: ^products_query],
    where:   order.id == ^order_id,
    select:  [order.savings, order.shipment_cost]
end

我也试过

def for_amount(order_id) do
  from order in Order,
    join:    products in assoc(order, :products),
    where:   order.id == ^order_id,
    select:  %{
                savings:       order.savings,
                shipment_cost: order.shipment_cost,
                quantity:      products.quantity,
                price:         products.price,
                discount:      products.discount,
              }
end

但这迫使我使用Repo.all并返回连接列表。

0 个答案:

没有答案