如何显示用户登录历史记录?

gos*_*scs 0 php laravel

我是Laravel的初学者。我在我的项目Laravel 5.8中使用。

我有这个架构:

Schema::create('user_login_histories', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->bigInteger('user_id')->unsigned();
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->dateTime('date_time');
    $table->ipAddress('ip');
    $table->engine = "InnoDB";
    $table->charset = 'utf8mb4';
    $table->collation = 'utf8mb4_unicode_ci';
});
Run Code Online (Sandbox Code Playgroud)

和我的模型:

class UserLoginHistory extends Model
{
    protected $quarded = ['id'];
    public $timestamps = false;
    protected $fillable = ['user_id', 'date_time', 'ip'];

    public function user()
    {
        return $this->belongsTo('App\User');
    }

    // Show User login history
    public function scopeHistory()
    {
        //return $this->hasMany('App\UserLoginHistory');
        return $this->hasMany('App\UserLoginHistory', 'user_id', 'id');
    }
}
Run Code Online (Sandbox Code Playgroud)

我想通过此功能显示用户历史记录:

public function getLoginAdminHistory(int $idAdmin)
{   
    return UserLoginHistory::history()->orderBy('id', 'desc')->paginate(25);
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用。

我怎样才能解决这个问题?

Sev*_*rin 5

您在此处使用范围的方式是错误的。它不打算那样使用,并且不会对您有帮助,因此我不会对此进行详细介绍。

我将假设您要为UserLoginHistory每个存储多个User,因此您需要的是类HasMany上的关系User

因此,要使其工作,您需要类似以下内容:

User.php

public function userLoginHistory(): HasMany
{
    return $this->hasMany(UserLoginHistory::class);
}
Run Code Online (Sandbox Code Playgroud)

现在您应该能够执行以下操作: $user->userLoginHistory,它将UserLoginHistory为您返回一个集合。

public function getLoginAdminHistory(int $idAdmin)
{   
    $user = User::findOrFail($idAdmin);
    return $user->userLoginHistory()->orderBy('id', 'desc')->paginate(25);
}
Run Code Online (Sandbox Code Playgroud)