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.

$companyOrders = CompanyOrders::where('id', $company_id)->get();
$users = [];
foreach($companyOrders as $companyOrder){
  $user = User::where('id', $companyOrder['user_id'])->first();
  array_push($users, $user);
}

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:

    public function companyOrders()
    {
        return $this->hasMany(AppCompanyOrders::class);
    }

In your CompanyOrders Model:

    public function user()
    {
        return $this->belongsTo(AppUser::class);
    }

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

User::whereHas('companyOrders', function($query) use ($company_id) {
    $query->where('id', $company_id);
})
->get();
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement