Laravel 关系 - 访问来自其他人的输入 table

Laravel Relationships - access input from other table

我无法正常工作。这应该很容易,但我不知道如何使用关系从不同 table 访问用户玩家标签。

这是我的 User.php 型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'gamertag', 'slug', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
    ];


    // A user has many messages (Chat)
    public function chat () {
        return $this->hasMany('App\Chat');
    }
}

这是我的 Chat.php 型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Chat extends Model {


    protected $table = "chat";


    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'message', 'user_id'
    ];


    // A Chat (or message) belong to a user
    public function user() {
        return $this->belongsTo('App\User');
    }


}

这就是我检索消息的方式:

class HomeController extends Controller {


    public function index () {

        $messages = Chat::orderBy('created_at', 'desc')->get();

        return view('layouts.index', compact('messages'));
    }

}

为什么我无法显示玩家标签?

@foreach($messages as $message)
     <a class="author">{{ $message->user->gamertag }}</a>
@endforeach

/***** 编辑***/

这个有效:

{{ dd($message->user->gamertag) }}




// This does NOT
{{ $message->user->gamertag }}

尝试使用预先加载:

$messages = Chat::orderBy('created_at', 'desc')->with('user')->get();

我想通了!这里一切正常,它只是在我的聊天 table 中,我插入了一条没有识别用户的消息,所以 user_id = 0,它正在抛出该错误。愚蠢的错误。