驗證資料是否存在

半人間發表於2019-12-20
        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 協議》,轉載必須註明作者和本文連結

相關文章