[英]getting two usernames based on ids from one row
So what I'm trying to do is this, basically I have a table called games which has 所以我想做的是,基本上我有一个叫做游戏的桌子
creator_id
and guest_id
creator_id
和guest_id
now what i want to do is when i want to list all games i want to join two tables and get for example if creator_id
is John and guest_id
is Mary 现在我想做的是当我想列出所有我想加入两张桌子的游戏时,例如,如果
creator_id
是John而guest_id
是Mary
i want to list all the "games" with their names 我想列出所有“游戏”及其名称
ID: 322 |
ID(标识号):322 | Creator Name: John |
创作者姓名:John | Guest Name: Mary
嘉宾姓名:玛丽
and so on, this is what i got so far: 等等,这就是我到目前为止所得到的:
Controller: 控制器:
class AdminController extends Controller
{
public function index()
{
return view('admin.home');
}
public function listGames()
{
$games = Game::get();
return view('admin.games.list', compact('games'));
}
}
View: 视图:
@extends('admin.content')
@section('title', 'List games')
@section('content')
<table class="table table-hover">
@foreach($games as $game)
// now i want to list that here
@endforeach
</table>
@endsection
Add relation methods in Game model 在游戏模型中添加关联方法
public function creator() {
return $this->hasOne(User::class, 'creator_id');
}
public function guest() {
return $this->hasOne(User::class, 'guest_id');
}
Eager load in your controller 控制器中的负载过大
public function index() {
$games = Game::with('creator', 'guest')->get();
return view('admin.games.list', compact('games'));
}
Now, in your view 现在,在您看来
@foreach($games as $game)
Creator: {{ $game->creator->name }}
Guest: {{ $game->guest->name }}
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.