Laravel Eloquent:判断数据是否存在 2 个改进

问题

如何判断表中是否存在指定的数据?

$user = User::where('email', '=', Input::get('email'));

如何判断 $user 有记录?

回答

这取决于您以后是否继续使用 $user,或者只判断是否存在用户记录。

如果你想看 $user 是否有记录:

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // 没记录
}

如果你只是想检查有没有记录

if (User::where('email', '=', Input::get('email'))->first()) {
   // 有记录
}

有更好的方法

if (User::where('email', '=', Input::get('email'))->exists()) {
   // 有记录
}
本文为 Wiki 文章,邀您参与纠错、纰漏和优化
讨论数量: 8

经验源于历练 :+1:

4年前 评论

isEmpty() get查询时可使用

4年前 评论
张雷

刚学编程的时候说用COUNT速度快,一直用到现在~

4年前 评论

这条不适用,慎用exitst(),
最好还是用count(),我用了一次,后来慢sql日志上全是exists,全部改成count了
以下是slowlog中的一条,如果用count()就会好很多

select exists(select * from `super_help_join` where (`super_help_id` = '6' and `user_id` = 129220) and `join_id` = 0 and `super_help_join`.`deleted_at` = 0) as `exists`;

# User@Host: aaa[bbb] @  [127.8.8.8]  Id: 1248754
# Query_time: 4.302264  Lock_time: 0.000027 Rows_sent: 0  Rows_examined: 151334
4年前 评论
保安 2年前

blank($user) 也不错

3年前 评论

exists()适用主键查询,或者根据唯一索引来查询。因为这个方法本质上查询全部数据,并且没有条数限制。很容易造成响应数据臃肿,造成慢SQL。

2年前 评论

结合 MySQL,最好符合以下几点要求:

1、WHERE 条件携带索引,索引优先顺序:主键 > 唯一 > 普通;

2、SELECT 仅查主键 ID;

3、LIMIT 1 限制仅返回1条;

4、判断返回数据是否为空即可;

5、复杂查询,另外根据情况优化。

1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!