我现在在三个模型之间有一个非常简单的关系。
def add_attribute_fields(self):
"""
For each attribute specified by the product class, this method
dynamically adds form fields to the product form.
"""
for attribute in self.instance.product_class.attributes.all():
field = self.get_attribute_field(attribute)
if field:
self.fields['attr_%s' % attribute.code] = field
订单需要有一个产品的数量,所以我目前正在做的是
class Customer: Object {
dynamic var customer_name = ""
}
class Product: Object {
dynamic var product_name = ""
}
class Order: Object {
dynamic var order_id = ""
dynamic var customer: Customer?
let products = List<Product>()
}
我想知道是否有另一种方法来指定class OrderProduct: Object {
dynamic var order: Order!
dynamic var product: Product!
dynamic var quantity: Int = 0
}
模型中的一个产品的数量,而不是创建Order
。
答案 0 :(得分:1)
不,到目前为止没有别的办法。 (在将来,您可能能够在字段中存储字典,这可能允许以不同方式解决。)
目前有以下两种可能性:
您在问题中描述的第一个,您在Order
上存储指向OrderProduct
的链接:
class Order: Object {
dynamic var order_id = ""
dynamic var customer: Customer?
let products = LinkingObjects(fromType: OrderProduct.self, property: "order")
}
class OrderProduct: Object {
dynamic var order: Order?
dynamic var product: Product?
dynamic var quantity: Int = 0
}
或者,您可以将关系存储在Order
:
class Order: Object {
dynamic var order_id = ""
dynamic var customer: Customer?
let products = List<OrderProduct>()
}
class OrderProduct: Object {
dynamic var product: Product?
dynamic var quantity: Int = 0
let orders = LinkingObjects(fromType: Order.self, property: "products")
var order: Order? { return orders.first }
}