У меня есть эти таблицы:
products
-- name
-- price
-- quantity
-- category_id
discounts
-- type('percentage','numeric')
-- value
-- expired_at
categories
-- name
discountables
-- discount_id
-- discountable_id
-- discountable_type
В discountables
существует множество отношений между многими:
discounts and categories
также discounts and products
Я закончил с тем, как сделать скидку между discounts and products
Теперь я запутался, Как сделать скидку на все товары, которые принадлежат категории, которую я добавляю к discountables
Отношение:
Категория Модели
public function discounts()
{
return $this->morphToMany('App\Models\Discount', 'discountable');
}
Модели продуктов
public function discounts()
{
return $this->morphToMany('App\Models\Discount', 'discountable');
}
Модель со скидкой:
public function categories()
{
return $this->morphedByMany('App\Models\Category', 'discountable')->withTimestamps();
}
public function products()
{
return $this->morphedByMany('App\Models\Product', 'discountable')->withTimestamps();
}
Мой код для скидки непосредственно на продукты discounts and products
/**
* get price of product after discount
*
* @return void
*/
public function getDiscountProductAttribute() {
foreach ($this->discounts as $discount) {
if($discount->expired_at > Carbon::now()){
if ($discount->type == 'numeric'){
return $this->price - $discount->value;
}else{
return $this->price - ($this->price * ($discount->value / 100));
}
}
}
}
Так что мне нужно Как сделать скидку на весь товар, который принадлежит категории, которую я добавляю к discountables
?