*/ public function bundle(): BelongsTo { return $this->belongsTo(Product::class, 'bundle_id'); } /** * @return BelongsTo */ public function product(): BelongsTo { return $this->belongsTo(Product::class); } /** * @return BelongsTo */ public function variant(): BelongsTo { return $this->belongsTo(ProductVariant::class, 'variant_id'); } /** * Make a bundle hold exactly these items, in this order. Not a bundle: pass an empty list. * * @param list $items */ public static function replaceFor(Product $bundle, array $items): void { $bundle->bundleItems()->delete(); foreach ($items as $position => $item) { $row = new self; $row->store_id = $bundle->store_id; $row->bundle_id = $bundle->id; $row->product_id = $item['product_id']; $row->variant_id = $item['variant_id']; $row->quantity = $item['quantity']; $row->position = $position; $row->save(); } $bundle->unsetRelation('bundleItems'); } /** * "Sambal Hijau (250g)". */ public function name(): string { return $this->product->name.($this->variant !== null ? ' ('.$this->variant->name().')' : ''); } /** * "2 × Sambal Hijau (250g)". */ public function label(): string { return $this->quantity.' × '.$this->name(); } /** * How many of this item are left: the variant's stock, or the product's. */ public function stock(): int { return $this->variant !== null ? $this->variant->stock : $this->product->stock; } /** * @return array */ protected function casts(): array { return [ 'quantity' => 'integer', 'position' => 'integer', ]; } }