2009-05-23 16 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

相關問題