I am creating a web store in SilverStripe from scratch without using a shop module. I am having trouble creating the shopping cart.
If I were to make a web store without any CMS system I would create 3 tables. A User
table, a Product
table and an Order
table.
In the Order
table there would be stored an ID
for the order, a UserID
that links to a user, a ProductID
that links to a product and a Quantity
.
Because I am using SilverStripe I can't directly do that. I can create tables like that but because it isn't the purpose of creating and running queries that is not the way to do it.
How do I do this correctly using SilverStripe?
I am aware of various opensource shopping modules for SilverStripe, but I found them confusing and I have no idea how they link to each other.
You can have SilverStripe create the database tables for you by extending its DataObject
and Page
classes.
The following code is for SilverStripe 3.1.
Here is how to create the User
, Product
and Order
classes to create the database tables you want, with the described relationships. I've also added in an OrderItem
class as I think it makes sense to.
class User extends DataObject {
private static $db = array(
'FirstName' => 'Text',
'LastName' => 'Text',
'Email' => 'Text'
);
}
class Product extends DataObject {
private static $db = array(
'Title' => 'Text',
'Price' => 'Decimal(19,8)'
);
}
class Order extends DataObject {
private static $has_one = array(
'User' => 'User'
);
private static $has_many = array(
'OrderItems' => 'OrderItem'
);
}
class OrderItem extends DataObject {
private static $has_one = array(
'Order' => 'Order',
'Product' => 'Product',
'Quantity' => 'Int'
);
}
Once you have created these classes run dev/build?flush=1
and then have a look at the tables that have been created in your database.
For Product
you could extend Page
instead of DataObject
if you wanted the products to be displayed as pages to the user. This is up to you.
Use SilverStripe to manage your classes, relationships and the database. That's what it is there for.
If you want an excellent shop module in SilverStripe I recommend checking out SwipeStripe. Or if you do want to build this yourself you can check out SwipeStripe's source code on git to see how they do things.