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

经验源于历练 :thumbsup:

6年前 评论

isEmpty () get 查询时可使用

6年前 评论
张雷

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

5年前 评论

这条不适用,慎用 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
5年前 评论
保安 3年前

blank ($user) 也不错

5年前 评论

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

3年前 评论

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

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

2、SELECT 仅查主键 ID;

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

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

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

2年前 评论