Laravel:无法访问?

问题描述 投票:1回答:2

我正在尝试访问User模型,但它返回空?

$topOnlineTime = UserStats::with('user')->orderBy('OnlineTime', 'DESC')->limit(10)->get();

在视图中:

@foreach ($topOnlineTime as $user)
{{ number_format($user->username) }}
@endforeach

usernamebelongs到用户模型

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');
    }
}
php laravel
2个回答
2
投票

由于UserStats有许多User记录,你需要迭代用户:

@foreach ($topOnlineTime as $userStats)
    @foreach ($userStats->user as $user)
        {{ $user->username }}
    @endforeach
@endforeach

1
投票

检查我在Laravel: Issue with relationship?上的答案,因为我认为你的循环的结果是返回null,因为你的迁移和关系没有正确设置。

以下是我提出这个问题的答案。我认为在确定之后@Alexy Mezenin的答案(https://stackoverflow.com/a/49082019/1409707)会起作用。

以下是我注意到您的代码的事情

  • 您的数据库结构错误。 (需要迁移来验证这一点)
  • 从可验证的扩展UserStatus
  • 你有保护身份证
  • 您的关系定义不正确。

要确认我们需要查看数据库结构和迁移。

如果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');
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.