【发布时间】:2018-05-30 20:04:18
【问题描述】:
我有一个专注于用户的控制器,它可以拥有许多客户(通过使用数据透视表)。目前(不起作用)这是我的控制器:
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'));
}
目前,我收到此错误:
此集合实例上不存在属性 [id]。
与$customerID = $customer->id这一行有关,显然是因为它可以返回多个实例。
我想要的是,如果用户有多个客户(例如 1、3 和 4),那么 $shipFromShipments 行搜索将在存在 1、3 或 4 的“ship_from”列中查找然后计算所有存在这些数字的行。
我使用单个值而不是多个值。
--更新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
}
]
}
【问题讨论】:
-
我建议先获取一个有效的原始 MySQL 查询。
-
dd($customer) after $customer = Auth::user()->customers and check
-
@Sohel0415 - 我已包含您要求的结果
标签: php mysql laravel laravel-5