我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
$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的全部目的。
其他回答
创建下面的方法(为自己),以检查给定的记录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);
有帮助!
我解决了这个问题,使用empty()函数:
$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
User::destroy($user->id);
$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
if($user->isEmpty()){
// has no records
}
Eloquent使用集合。 参见以下链接:https://laravel.com/docs/5.4/eloquent-collections
如果你想插入一个唯一的记录,你可以使用laravel验证:
$validated = $request->validate([
'title' => 'required|unique:usersTable,emailAddress|max:255',
]);
但是你也可以用这些方法:
1:
if (User::where('email', $request->email)->exists())
{
// object exists
} else {
// object not found
}
2:
$user = User::where('email', $request->email)->first();
if ($user)
{
// object exists
} else {
// object not found
}
3:
$user = User::where('email', $request->email)->first();
if ($user->isNotEmpty())
{
// object exists
} else {
// object not found
}
4:
$user = User::where('email', $request->email)->firstOrCreate([
'email' => 'email'
],$request->all());