我得到了这个按产品分类的销售集合:
$ventas = VentasProductos::withCount('producto')
->orderBy('producto_count', 'desc')
->take(5)
->get();
但是在视图中它向我显示了重复的元素,我创建了这行代码,但它并没有消除其中一个重复的元素:
if($ventas){
foreach($ventas as $key=>$venta){
if(array_key_exists($venta->id, $ventas)){
unset($ventas[$key]);
}
}
}
但显然我应用不正确array_key_exists
并且没有消除重复的元素。
#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 ▶}
]
}
而且应该只有一个
使用withCount函数,您可以获得与另一个表的关系产生的元素数量,而无需加载它们。问题是,当您从具有多对一关系的实体中调用它时,元素可以重复,主要是将您添加到结果中的新 *_count 属性将始终为 1。因此,我建议您从具有从 1 到许多关系的实体调用withCount,设法获取非重复元素以及与其他实体的实际关系数。