首页 > 解决方案 > 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
}

有什么建议么?

标签: phplaravel

解决方案


我是这样做的:

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);
        }

推荐阅读