首页 > 解决方案 > Laravel 编写查询以查找是否在日期启用了访问

问题描述

我有一张桌子叫system_access. 用户可以拥有访问权限,但必须启用它。访问可以被启用然后禁用,然后再次启用和禁用无限次。

我有一个名为的表audits,其中包含何时启用或禁用system_access.

我需要的是 - 在给定的时间内,我需要找到用户启用了哪些 system_accesses。

审计表具有以下结构:'id'、'action'、'system_access_id'、'created_at'。“动作”可以是“启用”或“禁用”

标签: mysqllaraveldate

解决方案


首先确保您的模型关系设置正确。

在您的 SystemAccess 模型中包括以下内容:

public function audits() {
    return $this->hasMany('App\Audits'); // Put the actual path of your model here
}

然后您可以使用 Eloquent 进行查询。一种方法(不是唯一的方法)是做这样的事情:

$access = SystemAccess::where('user_id', $userId)
->whereHas('audits', function($query) use($startDate,$endDate) {
    $query->where('status','enabled')
          ->where('created_at', '<=', $endDate)
          ->where('created_at', '>=', $startDate);
})->get();

第一个where通过用户 ID 获取所有 system_access 行。用于查询与审计表的whereHas关系,特别是我们要确保我们只在您指定的日期范围内(因此是$startDateand $endDate),并且如果启用它,也只检索状态。


推荐阅读