【发布时间】:2016-08-29 00:41:14
【问题描述】:
我无法正常工作。这应该很容易,但我不知道如何使用关系从不同的表访问用户玩家标签。
这是我的 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 }}
【问题讨论】:
-
$message->user 的输出是什么?
-
这太诡异了哈哈~
-
明天早上我会试着弄清楚
-
@David 你能告诉我你的数据库架构,或者聊天和用户表吗?
-
它可能工作正常,并且您有 另一个 变量导致错误。尝试 {{ @$messages->user->gamertag }} 看看错误是否仍然存在。如果是这样,那肯定不是那个引发异常的变量。
标签: php laravel eloquent relationship