John Davidson

php - Getting data from mutliple tables casuing duplicated data in view

0 comments
Message:


i am trying to display data from two different tables


Controller:


public function index()
{
$order = DB::table('order')->get();
$order_item = DB::table('order_item')->get();
return view('admin.orders', compact('order','order_item'));
}

View:


           @foreach ($order as $orders)
@foreach ($order_item as $order_items)
<tr>
<th style="padding: 20px">{{ $orders->id }}</th>
<th style="padding: 20px">{{ $order_items->order_id }}</th>

<th style="padding: 20px">&nbsp;<a><i style="color: #6565D8"
class="fa-solid fa-location-dot"></i></a>&nbsp;
&nbsp;<a><i style="color: #6565D8" class="fa-solid fa-eye"></i></a>&nbsp;
&nbsp;<a><i style="color: #6565D8" class="fa-solid fa-eye"></i></a>&nbsp;
</th>
</tr>
@endforeach
@endforeach

the problem in "$orders->id" it duplicate data to fulfill the same rows from the other table i am getting the same data (no duplicate) from "$order_items->order_id"


how to stop solve this issue?




My Answer:
>join('customer', 'order.customer_id', '=', 'customer.id')
->select('order.*', 'customer.name as customer_name')
->get();

return view('orders.index', compact('order'));
}_View:_@foreach($order as $o)

Order ID: {{ $o->id }}


Customer Name: {{ $o->customer_name }}


@endforeach

In this code, we are joining the 'order' table with the 'customer' table using the customer_id foreign key. This allows us to select data from both tables and display it in the view. However, if there are multiple orders for the same customer, the customer's name will be duplicated in the view.

To avoid this duplication, you can use the DISTINCT keyword in your query to only select unique customer names. Here's an updated version of the controller code:

php
$order = DB::table('order')
->join('customer', 'order.customer_id', '=', 'customer.id')
->select('order.*', DB::raw('DISTINCT customer.name as customer_name'))
->get();


With this change, only unique customer names will be selected, and the duplication issue should be resolved in the view.

Rate this post

4 of 5 based on 7076 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us