繁体   English   中英

从一行获取基于ID的两个用户名

[英]getting two usernames based on ids from one row

所以我想做的是,基本上我有一个叫做游戏的桌子

creator_idguest_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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM