我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
我刚来拉拉维尔。如何查找是否存在记录?
$user = User::where('email', '=', Input::get('email'));
我能做什么来查看$user是否有记录?
当前回答
你已经看到了很多解决方案,但是神奇的检查语法可以是这样的,
$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->isEmpty()){
// has no records
}
Eloquent使用集合。 参见以下链接:https://laravel.com/docs/5.4/eloquent-collections
if (User::where('email', 'user@email.com')->first()) {
// It exists
} else {
// It does not exist
}
如果只需要检查是否存在,请使用first(),而不要使用count()。
First()更快,因为它检查单个匹配,而count()计数所有匹配。
检查记录是否存在的有效方法必须使用is_null方法来检查查询。
下面的代码可能会有帮助:
$user = User::where('email', '=', Input::get('email'));
if(is_null($user)){
//user does not exist...
}else{
//user exists...
}
如果你想在数据库中插入一条记录,而相同邮件的记录不存在,那么你可以这样做:
$user = User::updateOrCreate(
['email' => Input::get('email')],
['first_name' => 'Test', 'last_name' => 'Test']
);
updateOrCreate方法的第一个参数列出了唯一标识关联表中的记录的列,而第二个参数由要插入或更新的值组成。
你可以在这里查看文档:Laravel upserts doc
要知道是否有记录是很简单的
$user = User::where('email', '=', Input::get('email'))->get();
if(count($user) > 0)
{
echo "There is data";
}
else
echo "No data";