Show your current query that isn't working
Joining Two Tables using Query Builder in Laravel
Hello I want to join two tables in laravel using query builder. I want to display the sku of particular product on the product page. I have tried but only first row is showing. Please can anyone help me in this issue. Below are the tables
products(id, name, price)
products_attributes(id, product_id(FK), sku)
products(1, toy1, 10) (2, toy2, 12)
products_attributes( 1, 1, 7866)(2, 2, 7767)
The reason why you are getting the first row is because of this [0] you see.. that will always return the first row no matter how many you have. I showed you a good way above, and I don't see a reason why not to use the models but the query builder instead.. if you want to use the query builder you still can, just reverse the joins:
$products = DB::table('products')
->select('products.id as product_id, products.name, products.price', 'products_attr.sku')
->join('products_attr','products.id','=','products_attr.product_id')
->get();
$products->firstWhere('product_id', 1)->sku ?? null;
Please or to participate in this conversation.