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

1 answer

Question: I have two tables how to fetch a customer's data using order's table user_id

  "order": [     {         "id": 1,         "user_id": 4     },     {         "id": 2,         "user_id": 5     }   ],     "customers": [         {             "id": 5,             "name": "Mohamed Raazi",             "phone": "777",         }     ], 

Following code will return only the last object of an array, i need to display all the objects from user table using a where condition in customers table

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

All answers to this question, which has the identifier 61136992

The best answer:

I would use the ::whereIn-method where you can provide an array of IDs to and get all the users with the provided IDs.

First you would have to reformat the $orders array that you have so that it contains only user IDs. I am guessing that you are using Eloquent to fetch the orders, then you can use the pluck-function in your Eloquent-statement:

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

Please note that the where-statement is not real, I just want to illustrate how you can call the pluck-method.

Another alternative is that you use the map function on the $orders-collection and return only user IDs:

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

Once you have your user IDs in an array/collection you can use it in the whereIn-statement:

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

Then this would give you all the users that that are connected to the orders you have in your order-collection.

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type is referenced as an interface from”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data