Laravel Relationships - 从其他表访问输入

时间:2016-08-28 05:12:05

标签: php laravel eloquent relationship

我不能让这个工作。这应该很简单,但我无法弄清楚如何使用关系从不同的表访问用户游戏玩家标签。

这是我的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 }}

enter image description here

2 个答案:

答案 0 :(得分:1)

尝试使用预先加载:

cat(c(nrow(df1), 2, 1), "\n", sep = "\t", file = f)
cat(df1$y, "\n", sep = "\t", file = f, append = TRUE)
cat(c("df1$x", "df1$y"), "\n", sep = "\t", file = f, append = TRUE)

答案 1 :(得分:0)

我明白了!一切都在这里工作,它只是在我的聊天表中,我插入了一条没有识别用户的消息,所以user_id = 0,并且它抛出了该错误。愚蠢的错误。