Creating and migrating the orders database
To store members’ orders, we need two tables. The first of them is the orders
table, which will store shipping details, member ID, and the total value of the order. The second one is the order_books
table. This table will store orders’ books and will be our pivot table. In this model, we’ll use thebelongsToMany()
relation. This is because an order can have many books. So, first we need an Order
model to store the book orders. Let’s create the Order.php
file under app
and add the following code:
<?php Class Order extends Eloquent { protected $table = 'orders'; protected $fillable = array('member_id','address','total'); public function orderItems() { return $this->belongsToMany('Book') ->withPivot('amount','total'); } }
As you can see in the code, we’ve used a new option named withPivot()
with thebelongsToMany()
function. With the withPivot()
function, we can fetch extra fields from our pivot table. Normally, without the function, the relational query accesses from the pivot table with just the id
object of related rows. This is necessary for our application because of price changes. Thus, previous orders, which were possibly done before any price change, are not affected.
Now we need a migration file to create the carts
table. To create a migration
file, give a command such as the following:
php artisan make:migration create_orders_table --table=orders --create
Open the migration file, which was created recently and located at database/migrations
. We need to edit the up()
function as follows:
public function up() { Schema::create('orders', function(Blueprint $table) { $table->increments('id'); $table->integer('member_id'); $table->text('address'); $table->decimal('total', 10, 2); $table->timestamps(); }); }
To apply migration, we need to migrate with the following artisan
command:
php artisan migrate
Let’s create our pivot
table. We need a migration file to create the order_books
table. To create a migration file, give a command such as the following:
php artisan make:migration create_order_books_table --table=order_books --create
Open the migration file, which was created recently and located at database/migrations
. We need to edit the up()
function as follows:
public function up() { Schema::create('order_books', function(Blueprint $table) { $table->increments('id'); $table->integer('order_id'); $table->integer('book_id'); $table->integer('amount'); $table->decimal('price', 10, 2); $table->decimal('total', 10, 2); }); }
To apply migration, we need to migrate with the following artisan
command:
php artisan migrate
Our database design and models are finished. Now we need to code controllers and our application’s front pages.