簡體   English   中英

使用 laravel 中的 where 線索從另一個表數據 id 檢索表中的數組 object

[英]Retrieve array object in a table from another table data id using a where clue in laravel

問題:我有兩個表如何使用訂單表 user_id 獲取客戶數據

  "order": [
    {
        "id": 1,
        "user_id": 4
    },
    {
        "id": 2,
        "user_id": 5
    }
  ],


  "customers": [
        {
            "id": 5,
            "name": "Mohamed Raazi",
            "phone": "777",
        }
    ],

以下代碼將僅返回數組的最后一個 object,我需要使用客戶表中的 where 條件顯示用戶表中的所有對象

        for ($x=0; $x<count($orders); $x++){
            $customer = User::where('id',$orders[$x]->user_id)->get(); 
        }

我會使用::whereIn -方法,您可以在其中提供一組 ID 並獲取所有具有所提供 ID 的用戶。

首先,您必須重新格式化您擁有的$orders數組,使其僅包含用戶 ID。 我猜您正在使用 Eloquent 來獲取訂單,然后您可以在 Eloquent-statement 中使用 pluck-function:

$userIds = Order::where('statement', true)->pluck('user_id')->toArray();

請注意 where 語句不是真實的,我只是想說明如何調用 pluck 方法。

另一種選擇是您在$orders -collection 上使用 map function 並僅返回用戶 ID:

$userIds = $orders->map(function ($order) {
    return $order->user_id;
});

在數組/集合中擁有用戶 ID 后,您可以在 whereIn 語句中使用它:

$users = Users::whereIn('id', $userIds)->get();

然后,這將為您提供與您的訂單集合中的訂單相關的所有用戶。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM