首页 > 解决方案 > 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 是什么,它似乎都会返回任何域。

标签: phplaravellaravel-query-builder

解决方案


我认为问题出在您的查询中。最后两个 where 应该分组。尝试以下操作:

Domains::where('user_id', $id)
       ->where(function ($query) {
           $query->whereNotNull('domain_last_notified_at')
                 ->orWhereNotNull('ssl_last_notified_at');
       })
       ->get();

推荐阅读