2017-07-05 36 views
0

那麼我想做到這一點,基本上我有一個表稱爲遊戲具有獲得兩個用戶名

creator_idguest_id

現在我想做的是當我要列出所有的比賽我要加入兩個表,並得到例如,如果creator_id是約翰和guest_id是瑪麗

我想列出所有的「遊戲」與他們的名字

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 
+0

放模型與你的問題及其相互關係碼 –

+0

請檢查下面 – Cadilab

回答

0

添加關係的方法在遊戲模式

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 
+0

答案我得到這個現在SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'users.creator_id'(SQL:select * from'users',其中'users'.'creator_id'在(14,15,16)和'users'.'leleted_at'中是空),我不知道爲什麼,但我沒有creator_id和guest_id在用戶表中,它在遊戲表@Sagar Chamling – Cadilab

+0

這應該工作。嘗試做'$ this-> hasOne(User :: class,'guest_id','id');'在兩種關係方法中。 –