关于php:具有2行和用户ID的关系

relations with 2 rows and user id

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

creator_id

guest_id

现在我想做的是列出所有我想加入两张桌子的游戏,例如creator_id是John而guest_id是Mary

我想列出所有名称为

的"游戏"

ID: 322 | Creator Name: John | Guest Name: Mary

依此类推,这就是我到目前为止所得到的:

控制器:

1
2
3
4
5
6
7
8
9
10
11
12
13
class AdminController extends Controller
{
    public function index()
    {
        return view('admin.home');
    }

    public function listGames()
    {
        $games = Game::get();
        return view('admin.games.list', compact('games'));
    }
}

查看:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@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

稍后我将其添加到游戏模型中

1
2
3
4
5
6
7
public function creator() {
    return $this->hasOne(User::class, 'creator_id');
}

public function guest() {
    return $this->hasOne(User::class, 'guest_id');
}

此给控制器

1
2
3
4
public function index() {
    $games = Game::with('creator', 'guest')->get();
    return view('admin.games.list', compact('games'));
}

并像这样循环

1
2
3
4
@foreach($games as $game)
    Creator: {{ $game->creator->name }}
    Guest: {{ $game->guest->name }}
@endforeach

但是随后发生了

SQLSTATE [42S22]:找不到列:1054'where子句'中的未知列'users.creator_id'(SQL:从(14,15,16)中users.creator_id和users.deleted_at为null的用户中选择* ),我不知道为什么,但是在用户表中没有creator_id和guest_id,在游戏表中没有


您正在混淆子模型和父模型。游戏没有用户-他们belongTo()他们,因为游戏表包含父母的ID。

相反,除非每个用户只能创建或玩一个游戏,否则应使用hasMany()而不是hasOne()


尝试将游戏模型的关系更改为:

1
2
3
4
5
6
7
public function creator() {
    return $this->belongsTo(User::class, 'creator_id');
}

public function guest() {
    return $this->belongsTo(User::class, 'guest_id');
}