mysql - Laravel 编写查询以查找是否在日期启用了访问
问题描述
我有一张桌子叫system_access
. 用户可以拥有访问权限,但必须启用它。访问可以被启用然后禁用,然后再次启用和禁用无限次。
我有一个名为的表audits
,其中包含何时启用或禁用system_access
.
我需要的是 - 在给定的时间内,我需要找到用户启用了哪些 system_accesses。
审计表具有以下结构:'id'、'action'、'system_access_id'、'created_at'。“动作”可以是“启用”或“禁用”
解决方案
首先确保您的模型关系设置正确。
在您的 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
关系,特别是我们要确保我们只在您指定的日期范围内(因此是$startDate
and $endDate
),并且如果启用它,也只检索状态。
推荐阅读
- java - 当您在 Firebase 上使用 .setPersistenceEnabled(true) 时,真的需要 .addOnCompleteListener 吗?
- c++ - 这种使用联合的类型别名是否会调用未定义的行为?
- node.js - Node.js 如何压缩图像数组并强制浏览器下载
- amazon-ec2 - nfs 目录始终以只读方式挂载,但 /etc/fstab 具有 rw 选项
- c# - 在 TextBox 中只允许 1 个符号
- jenkins - Jenkins 客户端证书认证
- reactjs - 反应原生 panResponder 动画
- html - 表单操作未在提交时重定向
- android - 获取通过OTG连接的存储的绝对路径
- c++ - gcc 是否支持宏定义中的多行原始字符串文字?