2017-03-02 65 views
1

我试图创建laravel查询,如果在电子邮件等于$电子邮件记录存在一个用户名,这将检查。我的表被称为用户。Laravel选择其中存在查询

我需要这个查询,因为当用户登记,他们只与他们的电子邮件地址和密码进行注册,并在以后的时间添加用户名,所以我需要检查,如果他们增加了一个用户名呢。

我已经在这里检查文档:https://laravel.com/docs/5.4/queries和无法理解我需要使用,任何人都可以帮助其查询?

回答

1

你可以这样做:如果你只需要检查是否存在不读取用户数据

$user = User::where('email', $email)->first(); 

if (empty($user->username)) { 
    // username is empty 
} else { 
    echo $user->username; 
} 
+1

完美的作品,谢谢! – JL9

0

我想你想要的东西是一样的东西$id = DB::table('user')->where('email', $email)->whereNotNull('username')->value('id');。这将返回匹配该电子邮件并且没有用户名的用户的ID,否则它将返回空值。那是你要求的吗?如果不是,你能澄清你的意思吗?

0

,更有效的方法是:

$exists=User::where('email', $email)->whereNotNull('username')->exists(); 
if ($exists) { 
    //User exists. No other data about it. 
} 

进行检查,并仅在读他的数据存在:

$user = User::where('email', $email)->whereNotNull('username')->first(); 

if (!$user) { 
    //Not found with username, maybe exists without it 
} 

如果想读它,然后检查数据:

$user = User::where('email', $email)->first(); 

if (!$user->username) { 
    //Does not exists even without username 
}else if (!$user->username) { 
    //Exists but without username 
}else{ 
    //Exists with username 
}