【问题标题】:Find rows in database where multiple values equal column value in Laravel在数据库中查找多个值等于 Laravel 中的列值的行
【发布时间】: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


【解决方案1】:

您似乎正在尝试从 collection 数组中获取单个 id

$customerID = $customer->id;

在上面的行中,预计它是一个集合,但有一个集合数组。这就是为什么它在此集合实例上获取 Property [id] 不存在错误。

确保您获得客户对象的单个实例。可能是这样的......

$customer = Auth::user()->customer;

或者使用 foreach 函数来获得 customer_id

【讨论】:

    猜你喜欢
    • 2015-05-25
    • 2015-05-24
    • 2020-04-12
    • 2021-12-29
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    相关资源
    最近更新 更多