如何在Laravel中展示具有相同属性值的数据
Let’s break this down based on your table structure and common use cases—whether you want to fetch all records matching a specific attribute value, or group records together by shared attribute values.
First, I’ll assume you have an Eloquent model set up for your table (let’s call it UserEvent for this example).
1. Fetch All Records with a Specific Attribute Value
If you want to show all users who share the same events value (like E01), use a simple where clause:
Controller Code
// Target the specific attribute value $targetEvent = 'E01'; // Fetch matching records $usersInEvent = UserEvent::where('events', $targetEvent)->get(); // Pass the data to your view return view('event-users', compact('usersInEvent'));
Blade View Display
Loop through the collection to render the table:
<table> <thead> <tr> <th>User Number</th> <th>User Name</th> <th>Event</th> <th>Register Date</th> </tr> </thead> <tbody> @foreach($usersInEvent as $user) <tr> <td>{{ $user->user_number }}</td> <td>{{ $user->user_name }}</td> <td>{{ $user->events }}</td> <td>{{ $user->register_date }}</td> </tr> @endforeach </tbody> </table>
2. Group All Records by an Attribute
If you want to group all records together by their events value (so you can see all users per event), use the groupBy() method:
Controller Code
// Fetch all records and group them by the 'events' column $usersGroupedByEvent = UserEvent::select('user_number', 'user_name', 'events', 'register_date') ->get() ->groupBy('events'); return view('grouped-events', compact('usersGroupedByEvent'));
Blade View for Grouped Data
Render each group separately:
@foreach($usersGroupedByEvent as $eventName => $users) <h3>Event: {{ $eventName ?? 'No Event Assigned' }}</h3> <table> <thead> <tr> <th>User Number</th> <th>User Name</th> <th>Register Date</th> </tr> </thead> <tbody> @foreach($users as $user) <tr> <td>{{ $user->user_number }}</td> <td>{{ $user->user_name }}</td> <td>{{ $user->register_date }}</td> </tr> @endforeach </tbody> </table> @endforeach
3. Handle Empty Attribute Values
If you want to exclude or focus on records with empty events values, adjust your query:
- Exclude empty events: Add
->whereNotNull('events')->where('events', '<>', '')to your query. - Only show empty events: Use
->whereNull('events')->orWhere('events', '').
Example: Exclude Empty Events
$usersWithValidEvents = UserEvent::whereNotNull('events') ->where('events', '<>', '') ->groupBy('events') ->get();
A quick heads-up: If you’re using MySQL and run into issues with groupBy, you might need to tweak the strict mode setting in config/database.php (set it to false temporarily) or use aggregate functions like count() if you need summarized data.
内容的提问来源于stack exchange,提问作者codespark

