我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
创建下面的方法(为自己),以检查给定的记录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);
有帮助!
其他回答
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
在if语句中检查null可以防止Laravel在查询结束后立即返回404。
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
如果找到用户,它似乎会运行双重查询,但我似乎找不到任何其他可靠的解决方案。
这有点晚了,但它可能会帮助那些试图使用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错误。
这是一个简单的代码来检查电子邮件是否存在数据库
$data = $request->all(); $user = DB::table('User')->pluck('email')->toArray(); if(in_array($user,$data['email'])) { echo 'existed email'; }
要知道是否有记录是很简单的
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";