:::
14-2 設定商品、購物車與買家的關聯
一、設定Cart的模型及關聯
- 從購物車(cart)的角度來看,每個購物車中的商品都有一個所屬(belongsTo)的商品(product),所以,開啟購物車的模型
/專案/app/Cart.php,加入對商品的belongsTo關聯:class Cart extends Model { public function product() { return $this->belongsTo('App\Product'); } public function user() { return $this->belongsTo('App\User'); } } - 此外,一個購物車,也一定會有一個買家,所以,我們也順便加入使用者的關聯。
- 設好後,日後只要取得
$cart資料,就可以順便帶出$cart->product商品資料,以及$cart->user使用者資料
二、設定商品對購物車的關聯
- 從商品(product)的角度來看,一個商品可能會對應到很多(hasMany)購物車(carts),所以,開啟商品的模型
/專案/app/Product.php,加入對購物車商品的hasMany關聯:class Product extends Model { public function getImageUrlAttribute() { if (Str::startsWith($this->attributes['image'], ['http://', 'https://'])) { return $this->attributes['image']; } return Storage::disk('public')->url($this->attributes['image']); } public function carts() { return $this->hasMany('App\Cart'); } } - 設定好關聯後,在取得
$product內容時,就會自動加入$product->cart資料陣列,可以輕鬆的取得此商品目前有多少被放在購物車中。
三、設定買家對購物車商品的關聯
- 原則上來說,一個買家可以有很多的(hasMany)購物車商品(carts),所以,開啟使用者的模型
/專案/app/User.php,加入對購物車商品的hasMany關聯:class User extends Authenticatable { use Notifiable; ...略... public function carts() { return $this->hasMany('App\Cart'); } } - 完整關聯請參考:https://learnku.com/docs/laravel/5.8/eloquent-relationships/3932
14-1 建立購物車的模型
