简体   繁体   中英

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

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

i want to list all the "games" with their names

ID: 322 | Creator Name: 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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