我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
可以用try/catch吗
->get()仍然返回一个空数组
其他回答
拉拉维尔 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
if ($u = User::where('email', '=', $value)->first())
{
// do something with $u
return 'exists';
} else {
return 'nope';
}
可以用try/catch吗
->get()仍然返回一个空数组
这取决于您是想在之后使用用户,还是只检查是否存在一个用户。
如果用户对象存在,你想使用它:
$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
// user doesn't exist
}
如果你只是想检查一下
if (User::where('email', '=', Input::get('email'))->count() > 0) {
// user found
}
或者更好
if (User::where('email', '=', Input::get('email'))->exists()) {
// user found
}
最好的解决方案之一是使用firstOrNew或firstOrCreate方法。文档中有更多关于这两者的详细信息。
在laravel雄辩中,有默认的exists()方法,参考下面的例子。
if (User::where('id', $user_id )->exists()) {
// your code...
}