Laravel选择存在查询的位置

时间:2017-03-02 17:36:59

标签: laravel laravel-5 laravel-query-builder

我正在尝试在laravel中创建一个查询,该查询将检查电子邮件是否等于$ email的记录中是否存在用户名。我的表名为User。

我需要这个查询,因为当用户注册时,他们只会注册他们的电子邮件地址和密码并在以后添加用户名,所以我需要检查他们是否添加了用户名。

我在这里检查了文档:https://laravel.com/docs/5.4/queries并且无法理解我需要使用哪个查询,有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

你可以这样做:

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

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

答案 1 :(得分:0)

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

答案 2 :(得分: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
}
相关问题