如何从Laravel中的数据库获取用户名?

时间:2018-07-20 10:13:05

标签: php mysql laravel

我是Laravel的初学者。我正在尝试按用户steam_id提取用户名。

我的表名为“ users”,“ match_players”和“ matches”。

users表具有名为“ steam_id”和“ username”的行。

match_players表具有一行“ steam_id”和“ match_id”。

matches表中还有一行名为“ match_id”的行。

我需要使用match_id> steam_id> username

来提取用户名

示例:

users表:

用户名:Paul | steam_id:0:0:045658

matches表:

match_id:d54gwdG566G

match_players表格:`

steam_id:0:0:045658 | match_id:d54gwdG566G

我尝试过类似的事情:

控制器:

$match->CTplayers = DB::table('match_players')->where('match_id', '=', $match->match_id)->where('team', '=', 1)->get();
$match->CTplayersSTEAM = DB::table('match_players')->where('match_id', '=', $match->match_id)->first()->steam_id;
$match->CTplayersID = User::where('steam_id', '=', $match->CTplayersSTEAM)->first()->username;

我的观点:

@foreach ($match->Tplayers as $Tplayer)
    <td>{{ $Tplayer->name }} {{ $match->CTplayersID }}</td>
    <td>{{ $Tplayer->kills }}</td>
    <td>{{ $Tplayer->deaths }}</td>
@endforeach

我知道代码不是很好,但是我只是在尝试和学习。

编辑

控制器:

            $match->CTplayers  = DB::table('match_players AS mp')
        ->leftJoin('users AS u', 'u.steam_id', '=', 'mp.steam_id')
        ->where('mp.match_id', '=', $match->match_id)
        ->where('team', '=', 1)
        ->select("mp.*", "u.username")
        ->get('');

刀片:

@foreach ($match->CTplayers as $CTplayer)
    <tr>
        <td>{{ $CTplayer->name }}</td>
        <td>{{ $CTplayer->kills }}</td>
        <td>{{ $CTplayer->deaths }}</td>
</tr>
@endforeach

3 个答案:

答案 0 :(得分:1)

您应该尝试加入: 我认为这段代码应该可以工作,但是我没有测试:

 $match->CTplayers  = DB::table('match_players AS mp')
                             ->leftJoin('users AS u', 'u.steam_id', '=', 'mp.steam_id')
                             ->where('mp.match_id', '=', $match->match_id)
                             ->select("mp.*", "u.username")
                             ->get();

在您看来,您会得到:

@foreach ($match->Tplayers as $Tplayer)
    <td>{{ $Tplayer->username }} {{ $match->CTplayersID }}</td>
    <td>{{ $Tplayer->kills }}</td>
    <td>{{ $Tplayer->deaths }}</td>
@endforeach

希望这会有所帮助

答案 1 :(得分:0)

您可以尝试加入,

AVMutableComposition

答案 2 :(得分:0)

在您的“比赛参与者”模型表中定义关系。

public function username()
{
    return $this->hasOne('App\Models\User', 'steam_id', 'steam_id');
}

然后在您的控制器中

$players = DB::table('match_players')->where('match_id', '=', $match->match_id)->where('team', '=', 1)->get();

foreach($players as $value)
{ 
   echo $value->username->username;
}

将为您获取用户名。