I've been trying to retrieve the data from multiple tables and it was clear and fine until I've faced the challenge to use the pivot tables (or link tables between manyToMany relationship tables).
So far, I can easily get a data from every single table, but I need to make just ONE query, which will take all the data I need.
Tables = products, details, categories, product_category (this one is a pivot table)
product_category = product_id | category_id (each one of these columns references on the id - product_id on products and category_id on categories)
Code to get queries:
$products = DB::table('products')
->join('details', 'products.id', '=', 'details.product_id')
->leftJoin('product_category', function($join) {
$join->on('products.id', '=', 'product_category.product_id');
})
->select('products.*', 'details.*', 'product_category.*')
->orderBy('products.created_at', 'desc')
->paginate(10);
Then on index page I can get all the data within foreach loop, but there's one tiny problem - I can only get the columns of product_category, in other words only category_id which references on categories.id - but I need to get those values from the categories table.
Please, don't give me a documentation or something like that, I research a lot every time before I ask a question and read at least a dozen of similar Q&A, but sometimes I need another point of view to get the solution and to understand how it works. Appreciate for every help.