I have an index() function on a controller that lists all of my users. Currently I can list all users, and values for the users but I can't get information from another table. Here is an an example of an SQL query I am trying to replicate in Eloquent.
SELECT user.id, user.name, user.email, user.title, timezones.name FROM users, timezones WHERE user.timezone=timezones.id
The way in which I currently display the users is:
$users = User::latest()->paginate(5); return view('users.index', compact('users'));
Table structure is as follows
Users Table:
id | name | email | timezone (int)
Timezone Table:
id | name
To output the data this is my index.blade.php file:
@foreach ($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->title }}</td>
<td>{{ $user->timezone }}</td>
</tr>
@endforeach
One way to do this would be to join
the timezones
table instead:
$users = User::select('user.id', 'user.name', 'user.email', 'user.title', 'timezones.name as timezone')
->join('timezones', 'user.timezone', 'timezones.id')
->latest()
->paginate(5);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.