簡體   English   中英

與2行和用戶ID的關系

[英]relations with 2 rows and user id

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

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

但這發生了

SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ users.creator_id”(SQL:從(14、15、16)中users.creator_id為null且users.deleted_at為null的用戶中選擇*),我不知道為什么,但是我在users表中沒有creator_id和guest_id,在games表中

嘗試將游戲模型的關系更改為:

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

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

您會混淆子模型和父模型。 本場比賽沒有用戶-他們belongTo()他們,因為游戲表包含了父母的ID。

反之,除非每個用戶只能創建或玩一個游戲,否則應使用hasMany()而不是hasOne()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM