php - Laravel 查询生成器获取用户登录记录
问题描述
我有一个 Laravel API,并且有一个在用户登录时运行的功能,当他们登录时,我想找到链接到他们的帐户的关联域,并根据是否发出域到期或 SSL 的通知来获取域到期。
我的代码正在运行,但我注意到的是,它正在查找所有域,而不管用户 ID 是什么,我只想为登录的用户获取域...
我在这里做错了什么?
/**
* Log In (log a user into the application)
*
* @param Request $request
* @return Response
*/
public function login(Request $request)
{
// update the last login at time
try {
$user = User::findOrFail(Auth::id());
$user->last_login_at = Carbon::now()->toDateTimeString();
$this->resetExpiryAlerts($user, Auth::id());
$user->save();
} catch (\Exception $e) { }
// success
return $this->respondWithToken($token);
}
/**
* Reset expiry alerts
*
*/
public function resetExpiryAlerts($user, $id)
{
$domains = Domains::where('user_id', $id)
->where('domain_last_notified_at', '!=', null)
->orWhere('ssl_last_notified_at', '!=', null)
->get();
if (count($domains) > 0) {
foreach ($domains as $key => $domain) {
if (
isset($domain->domain_last_notified_at) &&
($user->last_login_at >= $domain->domain_last_notified_at)
) {
$domain->domain_last_notified_at = null;
}
if (
isset($domain->ssl_last_notified_at) &&
($user->last_login_at >= $domain->ssl_last_notified_at)
) {
$domain->ssl_last_notified_at = null;
}
$domain->save();
}
}
}
我已经从我的示例中删除了一些不相关的代码,但我认为我在查询中做错了......
$domains = Domains::where('user_id', $id)
->where('domain_last_notified_at', '!=', null)
->orWhere('ssl_last_notified_at', '!=', null)
->get();
因为无论用户 ID 是什么,它似乎都会返回任何域。
解决方案
我认为问题出在您的查询中。最后两个 where 应该分组。尝试以下操作:
Domains::where('user_id', $id)
->where(function ($query) {
$query->whereNotNull('domain_last_notified_at')
->orWhereNotNull('ssl_last_notified_at');
})
->get();
推荐阅读
- python - 父函数未向多进程子进程发送正确的变量
- python - 如何将这些图像保存为灰度而不显示它们?
- html - 如何识别特定 DIV 的 ID,以便向其添加背景图像?
- javascript - 使用 JavaScript Observer 方法更改 aria 属性值
- python - Python Openpyxl 将 CSV 转换为 XLSX 并从包含数字的单元格中删除“$”
- excel - 无法使用 DAX 确定审计跟踪中的最新事件
- javascript - 将 D3 从 v4 升级到 v6 后,轴移动到图形中心
- azure - Terraform 天蓝色虚拟网络模块
- reactjs - 路由与导航栏下拉项 React react-bootstrap 中的链接 platform/:id 保持相同
- c++ - 非静态成员函数模板地址