简体   繁体   English

Laravel Eloquent 中的连接表值

[英]Join Table Values in Laravel Eloquent

I have an index() function on a controller that lists all of my users.我在 controller 上有一个 index() function,它列出了我的所有用户。 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.这是我试图在 Eloquent 中复制的 SQL 查询的示例。

SELECT user.id, user.name, user.email, user.title, timezones.name FROM users, timezones WHERE user.timezone=timezones.id 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); $users = User::latest()->paginate(5); return view('users.index', compact('users'));返回视图('users.index',紧凑('users'));

Table structure is as follows表结构如下

Users Table:用户表:

id |编号 | name |姓名 | email | email | timezone (int)时区(整数)

Timezone Table:时区表:

id |编号 | name姓名

To output the data this is my index.blade.php file:到 output 的数据是我的 index.blade.php 文件:

@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:一种方法是join timezones表:

$users = User::select('user.id', 'user.name', 'user.email', 'user.title', 'timezones.name as timezone')
    ->join('timezones', 'user.timezone', 'timezones.id')
    ->latest()
    ->paginate(5);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM