1.製作購物車結帳功能需要再新增兩個table 一個是order odersItem
php artisan make:migration create_orders_and_order_items
2.新增對應table ,且新增必要的欄位,這邊一個user會對應多個order(做foreignkey關聯),一個orders會跟carts產生關聯,一個購物車只會對應到一個訂單,並增加一個判斷該訂單是否被送出欄位,並設計一個default值為零(沒有送出)
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained('users');
$table->foreignId('cart_id')->constrained('carts');
$table->boolean('is_shipped')->default(0);
$table->timestamps();
});
Schema::create('order_items', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained('products');
$table->foreignId('order_id')->constrained('orders');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('orders');
Schema::dropIfExists('order_items');
}
3.設定order_items,每多個order_items對應一個product_id,一對多關係,然後他又會屬於belongTo訂單
4.接著設定drop,然後執行migrate
php artisan migrate
主要來做與資料庫關聯的設定
一個order對應多個orderItems 所以是一對多 使用hasMany
一個order對應一個user 所以是一對一 使用belongsTo
一個oder對應一個cart 使用belongsTo
5.接著來做MODEL資料夾下,先新增一個order.php,並做相關的關聯設定