Skip to content
Advertisement

SQL Query, or Eloquent Query a foreach loop

I have a question. Say I have two collections; CompanyOrders and User and need to do a loop to fetch all users involved in company orders, how would i do that? The example of a query that i am looking for will be provided below in a foreach format.

Now my next part wont work unless my $users is actually a collection. Hence the question, is there any way to query this so that $users = User::where(filters all users who are in various different company orders and gives me all in return)->get();

Points to Note

CompanyOrders has user_id, it’s the link between the company_orders table and the users table.

Thanks for your time and I would really appreciated any help provided! Cheers!

Advertisement

Answer

If you have built relationship

In your model User:

In your CompanyOrders Model:

you can use whereHas to find the user who has those companyOrders by $company_id:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement