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

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

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


当前回答

这将检查表中是否存在特定的电子邮件地址:

if (isset(User::where('email', Input::get('email'))->value('email')))
{
    // Input::get('email') exist in the table 
}

其他回答

$userCnt     = User::where("id",1)->count();
if( $userCnt ==0 ){
     //////////record not exists 
}else{
      //////////record exists 
}

注:其中条件根据您的要求。

if($user->isEmpty()){
    // has no records
}

Eloquent使用集合。 参见以下链接:https://laravel.com/docs/5.4/eloquent-collections

最短工作选项:

// if you need to do something with the user 
if ($user = User::whereEmail(Input::get('email'))->first()) {

    // ...

}

// otherwise
$userExists = User::whereEmail(Input::get('email'))->exists();

检查记录是否存在的有效方法必须使用is_null方法来检查查询。

下面的代码可能会有帮助:

$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
 //user does not exist...
}else{
 //user exists...
}

创建下面的方法(为自己),以检查给定的记录id是否存在于Db表中。

private function isModelRecordExist($model, $recordId)
{
    if (!$recordId) return false;

    $count = $model->where(['id' => $recordId])->count();

    return $count ? true : false;
}

// To Test
$recordId = 5;
$status = $this->isModelRecordExist( (new MyTestModel()), $recordId);

有帮助!