确定给定的外国 id 是否归用户所有?
Determine if the given foreign id is owned by the user?
确定给定的外部 ID 是否为用户所有以及 return 集合(如果找到)的好方法是什么?
我一直在这样做,比如在controller中:
public function showToken(Request $request)
{
$this->tokenRepo->ownToken($request->user(), $request->toke);
}
在 tokenRepo class 中,ownToken
方法如下所示:
public function ownToken($user, $tokenId)
{
return $user->tokens()->where('id', $tokenId)->first();
}
返回明确的 true
或 false
值是一个很好的做法。此外,如果您正在检查当前登录用户的令牌,您可以使用 auth()->user()
。例如,如果 repo 是一个模型:
public function ownToken($tokenId)
{
return is_null($this->where('id', $tokenId)
->where('user_id', auth()->user()->id)->first());
}
或:
public function ownToken($tokenId)
{
return is_null(auth()->user()->tokens()->where('id', $tokenId)->first());
}
那么你就可以这样做了:
if ($this->tokenRepo->ownToken($request->token)) { .... }
您可以 return 计数的布尔值大于零,这将减少数据库查询的权重。
public function ownToken($user, $tokenId)
{
return !! $user->tokens()->where('id', $tokenId)->count() > 0;
}
first()
将转换为 SELECT *
,其中 count()
将转换为 COUNT(id)
。
确定给定的外部 ID 是否为用户所有以及 return 集合(如果找到)的好方法是什么?
我一直在这样做,比如在controller中:
public function showToken(Request $request)
{
$this->tokenRepo->ownToken($request->user(), $request->toke);
}
在 tokenRepo class 中,ownToken
方法如下所示:
public function ownToken($user, $tokenId)
{
return $user->tokens()->where('id', $tokenId)->first();
}
返回明确的 true
或 false
值是一个很好的做法。此外,如果您正在检查当前登录用户的令牌,您可以使用 auth()->user()
。例如,如果 repo 是一个模型:
public function ownToken($tokenId)
{
return is_null($this->where('id', $tokenId)
->where('user_id', auth()->user()->id)->first());
}
或:
public function ownToken($tokenId)
{
return is_null(auth()->user()->tokens()->where('id', $tokenId)->first());
}
那么你就可以这样做了:
if ($this->tokenRepo->ownToken($request->token)) { .... }
您可以 return 计数的布尔值大于零,这将减少数据库查询的权重。
public function ownToken($user, $tokenId)
{
return !! $user->tokens()->where('id', $tokenId)->count() > 0;
}
first()
将转换为 SELECT *
,其中 count()
将转换为 COUNT(id)
。