Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

 
Reply to this topicStart new topic
> [PHP][Laravel]Zsumowanie wartości z tablic
Generic
post 26.05.2019, 18:45:36
Post #1





Grupa: Zarejestrowani
Postów: 224
Pomógł: 0
Dołączył: 31.10.2012

Ostrzeżenie: (10%)
X----


Mam następującą kolekcję z tablicami tak jak w poniższym kodzie. Próbuję uzyskać sumę wartości price ze wszystkich zwróconych tablic. Próbowałem zrobić to na kilka sposobów jednak za każdym razem otrzymuję błąd. Czy ktoś mógłby podpowiedzieć mi jak mogę uzyskać zamierzony efekt?

  1.  
  2. array_column($order->toArray(), 'product')
  3.  
  4. // Rezultat
  5.  
  6. array:2 [▼
  7. 0 => array:12 [▼
  8. "id" => 1
  9. "name" => "Fitness tracker"
  10. "price" => 75.99
  11. "created_at" => "2018-11-30 13:15:18"
  12. "updated_at" => "2019-01-16 20:59:21"
  13. ]
  14. 1 => array:12 [▶]
  15. ]
  16.  
Go to the top of the page
+Quote Post
Pyton_000
post 26.05.2019, 19:23:27
Post #2





Grupa: Zarejestrowani
Postów: 8 068
Pomógł: 1414
Dołączył: 26.10.2005

Ostrzeżenie: (0%)
-----


Kod
var_dump($order->sum('price'));


Dokumentacja nie gryzie

https://laravel.com/docs/5.8/collections#method-sum
Go to the top of the page
+Quote Post
Generic
post 26.05.2019, 20:05:19
Post #3





Grupa: Zarejestrowani
Postów: 224
Pomógł: 0
Dołączył: 31.10.2012

Ostrzeżenie: (10%)
X----


@Pyton_000

Niestety, użycie tej metody wyrzuca błąd - Call to a member function sum() on array.

  1.  
  2. var_dump(array_column($order->toArray(), 'product')->sum('price'))
  3.  
  4. // Rezultat
  5.  
  6. Call to a member function sum() on array.
  7.  
  8. var_dump(order->sum('price')
  9.  
  10. // Rezultat int(0)
  11.  


Go to the top of the page
+Quote Post
Pyton_000
post 26.05.2019, 20:11:57
Post #4





Grupa: Zarejestrowani
Postów: 8 068
Pomógł: 1414
Dołączył: 26.10.2005

Ostrzeżenie: (0%)
-----


Czym jest $order ?
Go to the top of the page
+Quote Post
Generic
post 26.05.2019, 20:28:41
Post #5





Grupa: Zarejestrowani
Postów: 224
Pomógł: 0
Dołączył: 31.10.2012

Ostrzeżenie: (10%)
X----


$order stanowi wynik z zapytania - Order::with('product')->where('id', $id)->get();

  1. Collection {#638 ▼
  2. #items: array:2 [▼
  3. 0 => Order {#634 ▼
  4. #table: "orders"
  5. #fillable: array:6 [▶]
  6. #connection: "mysql"
  7. #primaryKey: "id"
  8. #keyType: "int"
  9. +incrementing: true
  10. #with: []
  11. #withCount: []
  12. #perPage: 15
  13. +exists: true
  14. +wasRecentlyCreated: false
  15. #attributes: array:9 [▶]
  16. #original: array:9 [▶]
  17. #changes: []
  18. #casts: []
  19. #dates: []
  20. #dateFormat: null
  21. #appends: []
  22. #dispatchesEvents: []
  23. #observables: []
  24. #relations: array:1 [▼
  25. "product" => Product {#673 ▼
  26. #connection: "mysql"
  27. #table: "products"
  28. #primaryKey: "id"
  29. #keyType: "int"
  30. +incrementing: true
  31. #with: []
  32. #withCount: []
  33. #perPage: 15
  34. +exists: true
  35. +wasRecentlyCreated: false
  36. #attributes: array:12 [▼
  37. "id" => 1
  38. "Name" => "Fitness tracker"
  39. "price" => 75.99
  40. "created_at" => "2018-11-30 13:15:18"
  41. "updated_at" => "2019-01-16 20:59:21"
  42. ]
  43. #original: array:12 [▶]
  44. #changes: []
  45. #casts: []
  46. #dates: []
  47. #dateFormat: null
  48. #appends: []
  49. #dispatchesEvents: []
  50. #observables: []
  51. #relations: []
  52. #touches: []
  53. +timestamps: true
  54. #hidden: []
  55. #visible: []
  56. #fillable: []
  57. #guarded: array:1 [▶]
  58. }
  59. ]
  60. #touches: []
  61. +timestamps: true
  62. #hidden: []
  63. #visible: []
  64. #guarded: array:1 [▶]
  65. }
  66. 1 => Order {#635 ▶}
  67. ]
  68. }


Jak widać jest to złożona struktura, dlatego spróbowałem ją uprościć stosując array column.

Ten post edytował Generic 26.05.2019, 20:29:01
Go to the top of the page
+Quote Post
Pyton_000
post 26.05.2019, 20:34:34
Post #6





Grupa: Zarejestrowani
Postów: 8 068
Pomógł: 1414
Dołączył: 26.10.2005

Ostrzeżenie: (0%)
-----


$order->product->sum('price');
Go to the top of the page
+Quote Post
Generic
post 26.05.2019, 20:50:14
Post #7





Grupa: Zarejestrowani
Postów: 224
Pomógł: 0
Dołączył: 31.10.2012

Ostrzeżenie: (10%)
X----


Niestety zwraca błąd Property [product] does not exist on this collection instance. Wydaję mi się, że nie można w tym przypadku bezpośrednio odwołać się do product.
Go to the top of the page
+Quote Post
Pyton_000
post 26.05.2019, 22:00:02
Post #8





Grupa: Zarejestrowani
Postów: 8 068
Pomógł: 1414
Dołączył: 26.10.2005

Ostrzeżenie: (0%)
-----


zamień product na nazwę metody która odwołuje się do relacji oneToMany w modelu Order (ale bez nawiasów)
Go to the top of the page
+Quote Post
markonix
post 27.05.2019, 00:13:11
Post #9





Grupa: Zarejestrowani
Postów: 2 707
Pomógł: 290
Dołączył: 16.12.2008
Skąd: Śląsk

Ostrzeżenie: (0%)
-----


  1. Order::with('product')->where('id', $id)->get()->sum('product.price');


Abo utworzyć w modelu Order metodę getSummary() i w niej.
  1. $this->products->sum('price');


Ale wcześniej struktura do poprawy. Co to jest product? Zamówienie może mieć tylko tylko jeden, że w liczbie pojedynczej?
I jak to się ma do produktów w systemie? To powinna być tabela typu pivot łącząca katalog produktów, z produktem w zamówieniu.


--------------------
Go to the top of the page
+Quote Post
Generic
post 27.05.2019, 05:28:12
Post #10





Grupa: Zarejestrowani
Postów: 224
Pomógł: 0
Dołączył: 31.10.2012

Ostrzeżenie: (10%)
X----


@markonix, Order to kolumna, która zawiera klucz obcy id produktu z tabeli produkty. Do niej utworzyłem następującą relację:

  1. public function product() {
  2. return $this->belongsTo('App\Product', 'product_id', 'id');
  3. }


Go to the top of the page
+Quote Post
markonix
post 28.05.2019, 07:50:01
Post #11





Grupa: Zarejestrowani
Postów: 2 707
Pomógł: 290
Dołączył: 16.12.2008
Skąd: Śląsk

Ostrzeżenie: (0%)
-----


Chyba model?
Bez sensu nazwa, bo Order to Zamówienie więc główny obiekt, a do niego powinno być coś w stylu HasMany - OrderItem lub OrderProduct.


--------------------
Go to the top of the page
+Quote Post
Generic
post 2.06.2019, 15:43:28
Post #12





Grupa: Zarejestrowani
Postów: 224
Pomógł: 0
Dołączył: 31.10.2012

Ostrzeżenie: (10%)
X----


Struktura mojej bazy wygląda następująco:

Cart table (przechowuje informacje o zamówieniu):

id
user_id
shipping_id

Order table (przechowuje zamówione przedmioty):

id
user_id
product_id
quantity


User table (przechowuje dane klienta);

id
name
surname
etc.

Dla tabeli Cart utworzyłem relację Belongs to user z kluczem obcym user_id. Tabela Order zawiera relację Belongs to products z kluczem product_id. Struktura działa gdyż jestem w stanie pętlą foreach zwrócić zamówione przedmioty i dane klienta. Mam jednak problem ze zwróceniem wartości całego zamówienia.

Okey, dodałem zmienną:

  1. $total = Order::with('product')->where('id', $id)->get()->sum('product.price');



Działa tak jak tego oczekiwałem, jednak myślałem o tym by te informacje pochodziły z pierwotnego zapytania (tak jak poniżej), aby nie tworzyć nowego skoro są zawarte w jednym.

  1. Order::with('product')->where('id', $id)->get();


Ten post edytował Generic 2.06.2019, 15:44:28
Go to the top of the page
+Quote Post

Reply to this topicStart new topic
1 Użytkowników czyta ten temat (1 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Wersja Lo-Fi Aktualny czas: 16.04.2024 - 13:34