2009-05-23 18 views
4

如果我有两张表(客户和订单),并且我想查看客户的最新订单,那么我将如何使用GQL在Google App Engine上执行此操作?在Google App Engine上,我将如何查看GQL客户的最新订单?

通常,我会通过订单表中存在的外键customer_id将这两个表连接起来。

select orders.* from customers, orders 
where customers.customer_id = orders.customer_id 
and orders.order_id = (select top 1 sub_orders.order_id from orders sub_orders 
       where sub_orders.customer_id = orders.customer_id 
       order by sub_orders.order_date desc) 

但是,由于Google App Engine似乎无法加入联盟,因此我不确定如何解决此限制。任何建议,将不胜感激。

回答

10

Google App Engine中的DataStore与关系数据库真的很不相同。有一些相似之处,但在设计数据模型时理解差异很重要。

,你通常会定义这种关系的方法是使用引用属性:

class Customer(db.Model): 
    name = db.StringProperty() 

class Order(db.Model): 
    customer = db.ReferenceProperty(Customer, 
            collection_name = 'orders') 

在Order实体定义结果的ReferenceProperty在创作中的客户实体的属性,名为“订单” ,所以如果'customer'是一个Customer实例,你可以通过引用'customer.orders'来找到所有的订单。

例如:

customer = Customer.gql("WHERE name = :1", "Bob")[0] # Returns the first customer named Bob 
order1 = customer.orders[0] 
order2 = customer.orders.order("date")[0] # Sorts the Orders by date and gets the first one 

引用属性都记录here.

另一个重要的概念理解是实体组的想法。实体组中的实体存储在同一个节点上,因此可以更高效地存储和检索它们。它们对于使用交易也很重要。

+0

哇!这太棒了!谢啦。 – 2009-05-23 21:56:45

相关问题