我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
最短工作选项:
// 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();
其他回答
你已经看到了很多解决方案,但是神奇的检查语法可以是这样的,
$model = App\Flight::findOrFail(1);
$model = App\Flight::where('legs', '>', 100)->firstOrFail();
当没有找到任何相关模型时,它会自动引发一个响应404的异常,有时你可能希望在没有找到模型时抛出一个异常。这在路由或控制器中特别有用。fingernail和firstOrFail方法将检索查询的第一个结果;但是,如果没有找到结果,则会抛出一个Illuminate\Database\Eloquent\ModelNotFoundException异常。
裁判:https://laravel.com/docs/5.8/eloquent # retrieving-single-models
if (User::where('email', 'user@email.com')->first()) {
// It exists
} else {
// It does not exist
}
如果只需要检查是否存在,请使用first(),而不要使用count()。
First()更快,因为它检查单个匹配,而count()计数所有匹配。
if($user->isEmpty()){
// has no records
}
Eloquent使用集合。 参见以下链接:https://laravel.com/docs/5.4/eloquent-collections
我解决了这个问题,使用empty()函数:
$user = User::where('email', Input::get('email'))->get()->first();
//for example:
if (!empty($user))
User::destroy($user->id);
拉拉维尔 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