Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Google App Engine, how would I look up the latest order for a customer in GQL?

If I have two tables, Customers and Orders, and I want to look up the latest order for a customer, how would I do this on Google App Engine using GQL?

Normally, I would join these two tables through the foreign key, customer_id, which exists in the orders table.

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)

However, since joins do not seem to be possible on Google App Engine, I'm not sure how to work around this limitation. Any suggestions would be appreciated.

like image 840
pez_dispenser Avatar asked Dec 30 '22 23:12

pez_dispenser


1 Answers

The DataStore in Google App Engine is really quite different from a relational database. There are some similarities, but it's important to understand the differences when you design you data model.

The way you would normally define this kind of relationship is by using reference properties:

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

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

The ReferenceProperty in the Order entity definition results in the creation of a property in the Customer entity, named 'orders', so that if 'customer' is a Customer instance, you can find all the orders by referring to 'customer.orders'.

For example:

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

Reference properties are documented here.

Another important concept to understand is the idea of Entity Groups. Entities in an Entity Groups are stored on the same node, and therefore they can be stored and retrieved more efficiently. They're also crucial for using transactions.

like image 136
Ori Pessach Avatar answered Jan 01 '23 13:01

Ori Pessach