php - PHP检查数据库中是否存在
问题描述
我正在尝试检查我的数据库中是否存在某些内容。基本上我想为用户添加设备,如果它不存在,我正在尝试这样做:
public static function checkDevice($userId, $tokenId){
$devices = UserDevices::where('user_id', $userId)->get();
$notExists = '';
foreach ($devices as $key => $d) {
if(!$d->ip_address === SecureAgent::getIP() && $d->mac_address === SecureAgent::getMAC() && $d->device === SecureAgent::getDevice() ){
$notExists = 'User device not found!';
}
}
}
所以我需要检查这个 IP、Mac 和设备是否已经添加到数据库中,如果它们中的任何一个不相似,我将需要它们添加到数据库中,例如:
if($notExists === 'User device not found'){
self::addDevice() // I'm calling another function to do that job
}
有什么建议么?
解决方案
我是这样做的:
try {
UserDevices::where('user_id', $userId)->where('ip_address', SecureAgent::getIP())->where('mac_address', SecureAgent::getMac())->where('browser', SecureAgent::getSurfer())->firstOrFail();
} catch (\Exception $e) {
self::addDevice($userId, $tokenId);
}
推荐阅读
- bash - 将日期/时间值传递给 bash 函数中的触摸命令
- javascript - 如何保存 blob 并使用 wavesurfer 播放
- python - 数据框将现有列值更改为单个特定值
- azure-cognitive-search - Azure 认知搜索 - 通过 API 创建数据源
- sql - 将 varchar 值 ' 和 f.FUNCTION_ID= CAST(' 转换为数据类型 int 时转换失败
- javascript - 如何在 JavaScript 代码中添加 HTML 按钮?
- javascript - 反应打开文件对话框
- javascript - NodeJS Mocha 不会将参数传递给函数调用
- javascript - 在 GET 上发送嵌套对象
- swift - 当从一个视图控制器转到另一个视图控制器(如 Swift 中的 Instagram 或 Facebook)时,如何在表视图中保留当前的 IndexPath.row?