I got this collection of sales by products:
$ventas = VentasProductos::withCount('producto')
->orderBy('producto_count', 'desc')
->take(5)
->get();
but in the view it shows me the repeated elements, I created this line of code but it does not eliminate one of the repeated elements:
if($ventas){
foreach($ventas as $key=>$venta){
if(array_key_exists($venta->id, $ventas)){
unset($ventas[$key]);
}
}
}
But apparently I am applying the incorrectly array_key_exists
and the repeated element is not eliminated.
#items: array:4 [▼
0 => VentasProductos {#1791 ▼
+table: "ventas_productos"
+fillable: array:6 [▶]
#casts: array:7 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▶]
#original: array:10 [▼
"id" => 8
"cantidad" => 1
"importe" => 6.0
"importe_pagado" => 0.0
"deuda" => 1
"created_at" => null
"updated_at" => null
"producto_id" => 9
"factura_id" => 11
"producto_count" => 1
]
#changes: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
1 => VentasProductos {#1792 ▼
+table: "ventas_productos"
+fillable: array:6 [▶]
#casts: array:7 [▶]
#connection: "mysql"
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:10 [▼
"id" => 10
"cantidad" => 1
"importe" => 6.0
"importe_pagado" => 2.0
"deuda" => 1
"created_at" => "2018-03-26"
"updated_at" => "2018-03-27"
"producto_id" => 9
"factura_id" => 17
"producto_count" => 1
]
#original: array:10 [▼
"id" => 10
"cantidad" => 1
"importe" => 6.0
"importe_pagado" => 2.0
"deuda" => 1
"created_at" => "2018-03-26"
"updated_at" => "2018-03-27"
"producto_id" => 9
"factura_id" => 17
"producto_count" => 1
]
#changes: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: []
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
}
2 => VentasProductos {#1793 ▶}
3 => VentasProductos {#1794 ▶}
]
}
And there should be only one
With the withCount function you get the number of elements resulting from the relationship with another table, without having to load them. The problem is that when you call it from the entity that has the many-to-one relationship, elements can be repeated and mainly the new *_count property that will add you to the results will always be 1. Therefore, I recommend that you call withCount from the entity that has the relationship from 1 to many, managing to obtain non-repeating elements and the actual number of relationships with the other entity.