![](/img/trans.png)
[英]Php mysql Query two usernames in one row based on id from another table
[英]getting two usernames based on ids from one row
所以我想做的是,基本上我有一個叫做游戲的桌子
creator_id
和guest_id
現在我想做的是當我想列出所有我想加入兩張桌子的游戲時,例如,如果creator_id
是John而guest_id
是Mary
我想列出所有“游戲”及其名稱
ID(標識號):322 | 創作者姓名:John | 嘉賓姓名:瑪麗
等等,這就是我到目前為止所得到的:
控制器:
class AdminController extends Controller
{
public function index()
{
return view('admin.home');
}
public function listGames()
{
$games = Game::get();
return view('admin.games.list', compact('games'));
}
}
視圖:
@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
在游戲模型中添加關聯方法
public function creator() {
return $this->hasOne(User::class, 'creator_id');
}
public function guest() {
return $this->hasOne(User::class, 'guest_id');
}
控制器中的負載過大
public function index() {
$games = Game::with('creator', 'guest')->get();
return view('admin.games.list', compact('games'));
}
現在,在您看來
@foreach($games as $game)
Creator: {{ $game->creator->name }}
Guest: {{ $game->guest->name }}
@endforeach
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.