Получите сумму моделей отношений polymorphi c, умноженную на pivot - PullRequest
0 голосов
/ 04 августа 2020

При использовании полиморфных c отношений, как я могу получить сумму поля преобразованной модели, умноженную на значение поворота?

Итак, у меня есть эти таблицы:

- order (hasMany OrderItems)
    - ...
- order_item (morphTo)
    - orderable_id
    - orderable_type
    - quantity
product_type_a
    - price
    - ...
product_type_b
    - price
    - ...
product_type_c
    - price
    - ...

Это модели:

class Order extends Model
{
    public function items()
    {
        return $this->hasMany(OrderItem::class);
    }
}

class OrderItem extends Model
{
    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function orderable()
    {
        return $this->morphTo();
    }
}

class ProductType extends Model
{
    public function orderItem()
    {
        return $this->morphOne(OrderItem::class, 'orderable');
    }
}

Я пытаюсь получить сумму order_item.quantity × order_item.orderable.price.

Я попытался, просто чтобы увидеть результат, эти запросы ($this в данном контексте относится к модели Order):

$this->items()->with('orderable')->sum('quantity');

Что возвращает ожидаемую сумму количества order_items.

$this->items()->with('orderable')->sum('price');
$this->items()->with('orderable')->sum('orderable.price');
$this->items()->with('orderable')->sum(DB::raw('price'));
$this->items()->with('orderable')->sum(DB::raw('orderable.price'));

Где все результаты (похожие ошибки, но в основном неизвестные столбцы):

Column not found: 1054 Unknown column 'price' in 'field list' (SQL: select sum(price) as aggregate from `order_items` where `order_items`.`order_id` = ? and `order_items`.`order_id` is not null and `order_items`.`deleted_at` is null)

Итак, я не могу получить доступ даже к сумме цен преобразованные модели. Как можно достичь суммы order_item.quantity × order_item.orderable.price. Так, например:

product_type_a
    - id: 1
    - price: 1.00

product_type_b
    - id: 2
    - price: 2.00

order_item
    - quantity: 5
    - orderable_id: 1
    - orderable_type product_type_a

order_item
    - quantity: 10
    - orderable_id: 2
    - orderable_type product_type_b

Сумма должна быть (5 * 1.00) + (10 * 2.00) = 25

1 Ответ

1 голос
/ 04 августа 2020

Я думаю, вы могли бы использовать аксессор, чтобы сделать magi c.

class OrderItem extends Model
{
    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function orderable()
    {
        return $this->morphTo();
    }

    public function getCalculatedPriceAttribute(): int
    {
        return $this->quantity * $this->orderable->price;
    }
}
$order = Order::with('items.orderable')->find($id);

$total = $order->items->sum('calculated_price');

Если я не ошибаюсь, вы можете go на один шаг дальше и сделать часть суммы также аксессуар.

class Order extends Model
{
    public function items()
    {
        return $this->hasMany(OrderItem::class);
    }

    public function getCalculatedTotalAttribute(): int
    {
        return $this->items->sum('calculated_price');
    }
}
$order = Order::with('items.orderable')->find($id);

$total = $order->calculated_total;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...