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

pez*_*ser 4 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)
Run Code Online (Sandbox Code Playgroud)

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

Ori*_*ach 10

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

通常使用引用属性定义这种关系的方式如下:

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

class Order(db.Model):
   customer = db.ReferenceProperty( Customer,
                                    collection_name = 'orders' )
Run Code Online (Sandbox Code Playgroud)

Order实体定义中的ReferenceProperty导致在Customer实体中创建一个名为'orders'的属性,因此如果'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
Run Code Online (Sandbox Code Playgroud)

此处记录参考属性.

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