我有以下型号
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
我现在要做的是获取具有特定字段的订单:savings
和shipment_cost
.
我还需要该订单的关联产品,但同样,也只有特定字段quantity
:price
和discount
。
如何以最有效的方式做到这一点?
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
当然迫使我使用并返回一个连接列表。