我刚来拉拉维尔。如何查找是否存在记录?

$user = User::where('email', '=', Input::get('email'));

我能做什么来查看$user是否有记录?


当前回答

if (User::where('email', 'user@email.com')->first()) {
    // It exists
} else {
    // It does not exist
}

如果只需要检查是否存在,请使用first(),而不要使用count()。

First()更快,因为它检查单个匹配,而count()计数所有匹配。

其他回答

我认为下面的方法是达到同样目的的最简单的方法:

    $user = User::where('email', '=', $request->input('email'))->first();
    if ($user) {
       // user exist!
    }else{
       // user does not exist
    }

这有点晚了,但它可能会帮助那些试图使用User::find()->exists()来记录存在的人,因为Laravel为find()和where()方法显示了不同的行为。假设电子邮件是你的主键,让我们来看看这种情况。

$result = User::find($email)->exists();

如果存在该电子邮件的用户记录,则返回true。然而,令人困惑的是,如果不存在该电子邮件的用户,那么它将抛出一个错误。即

Call to a member function exists() on null.

但是where()的情况是不同的。

$result = User::where("email", $email)->exists();

如果记录存在,上面的子句将返回true,如果记录不存在则返回false。因此,总是尝试使用where()来表示记录是否存在,而不使用find()来避免NULL错误。

if (User::where('email', Input::get('email'))->exists()) {
    // exists
}
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

可以写成

if (User::where('email', '=', Input::get('email'))->first() === null) {
   // user doesn't exist
}

这将返回true或false,而不分配临时变量,如果这是你在原始语句中使用$user的全部目的。

拉拉维尔 5.6.26v

通过主键(电子邮件或id)查找现有记录

    $user = DB::table('users')->where('email',$email)->first();

然后

      if(!$user){
             //user is not found 
      }
      if($user){
             // user found 
      }

包括“use DB”和表名user变成复数,使用上面的查询,就像user变成users