在Google App Engine上,如何在GQL中查找客户的最新订单?

时间:2009-05-23 21:19:09

标签: google-app-engine join gql

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

通常,我会通过订单表中存在的外键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似乎无法进行加入,因此我不确定如何解决此限制。任何建议将不胜感激。

1 个答案:

答案 0 :(得分: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实体中创建一个名为'orders'的属性,因此如果'customer'是Customer实例,您可以通过引用'customer'来查找所有订单。命令'。

例如:

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.

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