Support the ongoing development of Laravel.io →
posted 8 years ago
Eloquent
Last updated 1 year ago.
0
Company::with('users')->with('products')->get();

That actually gives you the 2 associated tables AND the pivot table. Example:

$companies = Company::with('users')->with('products')->get();

// First loop through the companies
foreach ($companies as $company) {

    // Then loop through the company's users
    foreach ($company->users as $user) {
        // Access company_user pivot table like this:
        $pivot = $user->pivot;
    }

}

If you also want the company_products pivot table as well, then change the query and add it to the with method:

$companies = Company::with('users', 'products')->with('products')->get();
Last updated 8 years ago.
0

Thanks @thomastkim for your reply

Sorry, I didn't explain what I was trying to query in detail. What I would like to get in the end is the list of company_user where user_id=Auth::id(), and the array of products for each of the company, hence the second query to find(Auth::id()), but somehow attaching the products array for each company as well. Hope I have explained it clearly.

0

I think I understand. Let me know if this is what you want.

You want to get the user's companies and from those companies, you want to get each company's products. Laravel makes that relatively easy with eager loading and the dot notation.

$user = User::with('companies.products')->find(Auth::id());

You can then get each company by doing this:

foreach ($user->companies as $company) {

    // Access to each user's company

    foreach ($company->products as $product) {

        // Access to the company's products

    }
}
0

Thanks @thomastkim! I ended up using this instead

$companies = User::find(Auth::id())->companies()->with(['products'=> function ($query) {
    $query->get(['product_name'])->toArray();
}]);

Not sure if its the most efficient way, but it is working for now. Thanks again!

0

Sign in to participate in this thread!

Eventy

Your banner here too?

adrielzxdf adrielzxdf Joined 13 Nov 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.