我正在尝试访问User
模型,但它返回空?
$topOnlineTime = UserStats::with('user')->orderBy('OnlineTime', 'DESC')->limit(10)->get();
在视图中:
@foreach ($topOnlineTime as $user)
{{ number_format($user->username) }}
@endforeach
username
belongs到用户模型
class UserStats extends Authenticatable
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function user()
{
return $this->hasMany(User::class, 'id');
}
}
这是用户模型
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function userStats() {
return $this->belongsTo(UserStats::class, 'id');
}
}
由于UserStats
有许多User
记录,你需要迭代用户:
@foreach ($topOnlineTime as $userStats)
@foreach ($userStats->user as $user)
{{ $user->username }}
@endforeach
@endforeach
检查我在Laravel: Issue with relationship?上的答案,因为我认为你的循环的结果是返回null,因为你的迁移和关系没有正确设置。
以下是我提出这个问题的答案。我认为在确定之后@Alexy Mezenin的答案(https://stackoverflow.com/a/49082019/1409707)会起作用。
以下是我注意到您的代码的事情
要确认我们需要查看数据库结构和迁移。
如果userstat有很多用户且用户属于1 userstat。
迁移将是
users表将有user_stat_id,userstats表将没有user_id
代码看起来像这样。
UserStatus.php
class UserStats extends Model
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function users()
{
return $this->hasMany(User::class, 'user_stat_id');
}
}
user.php的
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function stat() {
return $this->belongsTo(UserStats::class, 'user_stat_id');
}
}