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();
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.
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
}
}
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!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community