1.首先先設定user level ,定義user level 2 為VIP,
為order_items添加新的欄位,當他是VIP時享受優惠價格,故創建migration
php artisan make:migration add_discount_to_order_items
2.增加price欄位及user層級(default值為1),接著執行migrate
public function up()
{
Schema::table('order_items', function (Blueprint $table) {
$table->integer('price')->after('order_id');
});
Schema::table('users', function (Blueprint $table) {
$table->integer('level')->default(1)->after('id');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('order_items', function (Blueprint $table) {
$table->dropColumn('price');
});
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('level');
});
}
3.接著來到Cart Model修正
首先先定義一個private(私有變數) = $rate 1
額外理解關於PHP OOP
private $rate = 1;
4.接著設計當user 等級來到 level 2 的時候其rate =0.8 所以在foreach前面定義一個 if 條件式
if($this->user->level == 2){
$this->rate = 0.8;
}
5.最後修改orderItem()函數 欄位price = price * rate
foreach($this->cartItems as $cartItem){
$order->orderItems()->create([
'product_id' => $cartItem->product_id,
'price' => $cartItem->product->price * $this->rate
]);
6.全部程式碼為
7.接著進行測試,首先將User等級改為Level 2 執行POSTMAN結帳功能
8.結帳後可以看到OrderItem價格改變