验证数据是否存在 
                                                    
                        
                    
                    
  
                    
                            DB::enableQueryLog();
        if (User::where('role_id', 1)->first()) {
            dump('存在');
        }
        if (User::where('role_id', 1)->exists()) {
            dump('存在');
        }
        dd(DB::getQueryLog());
SQL
array:2 [
  0 => array:3 [
    "query" => "select * from `users` where `role_id` = ? limit 1"
    "bindings" => array:1 [
      0 => 1
    ]
    "time" => 20.23
  ]
  1 => array:3 [
    "query" => "select exists(select * from `users` where `role_id` = ?) as `exists`"
    "bindings" => array:1 [
      0 => 1
    ]
    "time" => 19.58
  ]
]
发现第二种查询明显快过第一种。
本作品采用《CC 协议》,转载必须注明作者和本文链接
          
                    
                    
,这是通过 explain 进行分析的,你的role_id 是关联表的主键, 我这也是关联表的主键; 你可以自行尝试,这 孙子开挂,怎么和他比 :sweat:
          
          
                关于 LearnKu
              
                    
                    
                    
 
推荐文章: