[英]How to join two tables in Laravel
I'm trying to join two different tables to display in the foreach loop in my index.blade
file我正在尝试加入两个不同的表以显示在我的
index.blade
文件的 foreach 循环中
My Controller:我的控制器:
public function index()
{
$users = DB::table('accounts')
->join('users', 'accounts.user_id', '=', 'users.id')
->select('users.accno', 'accounts.*')
->first();
return view('accounts.index', compact('users'));
}
My blade:我的刀片:
@foreach($users as $user)
<tr>
<td>{{ $user->accno }}</td>
<td>{{ $user->balance }}</td>
<td>{{ $user->amt }}</td>
</tr>
@endforeach
My index.blade.php where I'm implementing the controller, the {{user->accno}}
is from my user table and the rest is from accounts table我正在实现控制器的
{{user->accno}}
, {{user->accno}}
来自我的用户表,其余来自帐户表
$users = DB::table('accounts')
->join('users', 'accounts.user_id', '=', 'users.id')
->select('users.accno', 'accounts.*')
->first();
In your controller, you are using for first()
.在您的控制器中,您使用的是 for
first()
。 So need to use foreach
.所以需要使用
foreach
。 Just write:写就好了:
<tr>
<td>{{ $user->accno }}</td>
<td>{{ $user->balance }}</td>
<td>{{ $user->amt }}</td>
</tr>
Or you should use get()
instead of first()
.或者你应该使用
get()
而不是first()
。 But it depends on your data if you want return only one data you should use first().但是,如果您只想返回一个应该使用 first() 的数据,这取决于您的数据。 If you want to return a lot of data you should use get().
如果你想返回大量数据,你应该使用 get()。 Controller:
控制器:
$users = DB::table('accounts')
->join('users', 'accounts.user_id', '=', 'users.id')
->select('users.accno', 'accounts.*')
->get();
Blade:刀刃:
@foreach($users as $user)
<tr>
<td>{{ $user->accno }}</td>
<td>{{ $user->balance }}</td>
<td>{{ $user->amt }}</td>
</tr>
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.