我有一个专注于用户的控制器,可以拥有许多客户(通过使用数据透视表)。目前(这不起作用)这是我的控制器:
public function index()
{
$customer = Auth::user()->customers;
$customerID = $customer->id;
$shipFromShipments = shipment::where('ship_from', '=', $customerID)->get();
$shipFromShipmentsCount = $shipFromShipments->count();
$shipToShipments = shipment::where('ship_to','=', $customerID)->get();
$shipToShipmentsCount = $shipToShipments->count();
$billToShipments = shipment::where('bill_to', '=', $customerID)->get();
$billToShipmentsCount = $billToShipments->count();
$customersCount = $customer->count();
return view('home', compact('customer','shipFromShipmentsCount','shipToShipmentsCount','billToShipmentsCount','customersCount'));
}
目前,我收到此错误:
此集合实例上不存在Property [id]。
与行$customerID = $customer->id
相关,显然是因为它可以返回多个实例。
我想要的是,如果用户有多个客户(比如1,3和4),那么$shipFromShipments
行搜索将在“ship_from”列中查找1,3或4存在然后得到任何这些数字存在的所有行的计数。
我用单个值完成了这个,但不是多个。
- 更新dd($ customer)
Collection {#310 ▼
#items: array:1 [▼
0 => customer {#309 ▼
#fillable: array:19 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:34 [▶]
#original: array:36 [▶]
#changes: []
#casts: []
#dates: []
#dateFormat: null
#appends: []
#dispatchesEvents: []
#observables: []
#relations: array:1 [▶]
#touches: []
+timestamps: true
#hidden: []
#visible: []
#guarded: array:1 [▶]
#excludedAttributes: []
#auditEvent: null
}
]
}
答案 0 :(得分:1)
似乎您试图从数组的集合中获取单个 id 。
$customerID = $customer->id;
在上面一行中,预计它是一个单独的集合,但有一系列的集合。这就是为什么在此集合实例错误中不存在Property [id]。
确保获得单个客户对象实例。可能是以下......
$customer = Auth::user()->customer;
或使用 foreach 功能获得 customer_id