A
A
Andrey Boychenko2019-01-21 23:34:02
Laravel
Andrey Boychenko, 2019-01-21 23:34:02

Laravel and data into relationships?

Goodnight! I have the following task.
To the front, you need to display a table with three levels of nesting
1. Customer
2. Amount (Total amount of all orders)
2.1 Order number
2.2 Order amount (Amount of cost of goods)
3.1 Name
3.2 Price
3.3 Quantity
3.4 Amount
For this I have the following database structure (Missing some fields)
Users
1.id
2.name
penalty_orders
1.id
2.user_id
3.order_id
penalty_products
1.id
2.qty
3.product_id
First, I make a selection with a condition
Client::whereHas('relatedOrders')
Thus, I get clients whose penalty_orders table is not empty. Also I deduce them in representation, but already here also there is a problem. Because I have to display the values ​​for a particular user.

@foreach($clients as $client)
            Клиент: {{ $client->first_name }} {{ $client->last_name }}

        @foreach ($client->relatedOrders as $order)
            @foreach ($order->relatedProducts as $product)
                @php($a[] = $product->qty*$product->relatedPenalty->price)
            @endforeach
        @endforeach

        Сумма: {{ array_sum($a) }}
@endforeach

This code will display the correct value for me, provided that there is only one user in the database with the relatedOrders relation, if there are more of them, then the value will be correct only at the first iteration.
Please explain how I can take a value that is actually inside a relation, which in turn is a relation. The request code looks like this. The matter is that I want to solve all this business, only one request.
$clients = Client::whereHas('relatedOrders')->with('relatedOrders.relatedProducts.relatedPenalty','relatedOrders.relatedProducts.relatedProduct')->latest()->get();

Thanks a lot for any help!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
vism, 2019-01-22
@Ka4_Piton

In the code, it's great for a person not to go through this

@foreach ($client->relatedOrders as $order)
            @foreach ($order->relatedProducts as $product)
                @php($a[] = $product->qty*$product->relatedPenalty->price)
            @endforeach
        @endforeach
in representation At
least it is necessary to do it in service/model by a separate method and to deduce.
And it is getTotalOrdersProductsPenaltyPrice , otherwise you will understand your code later.

D
DmitrSha, 2019-01-21
@DmitrSha

probably reset $a for each client when outputting,
or at least tell us what are the wrong values ​​​​and what they become

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question