백엔드/laravel

query builder에서 select

janggos 2024. 1. 14. 11:19
  1. DB::table('users')->select('name', 'email')->get();
    • users 테이블에서 name 및 email 열의 값을 선택하여 모든 행을 가져옵니다.
    • SQL: SELECT name, email FROM users;
  2. DB::table('posts')->select('title as post_title')->get();
    • posts 테이블에서 title 열을 post_title로 별칭 지어 선택하여 모든 행을 가져옵니다.
    • SQL: SELECT title AS post_title FROM posts;
  3. DB::table('posts')->distinct()->get();
    • posts 테이블에서 중복된 값을 제외한 모든 행을 가져옵니다.
    • SQL: SELECT DISTINCT * FROM posts;
  4. DB::table('posts')->select('is_published')->distinct()->get();
    • posts 테이블에서 is_published 열의 중복된 값을 제외하고 가져옵니다.
    • SQL: SELECT DISTINCT is_published FROM posts;
  5. $posts = DB::table('posts')->select('title'); $added = $posts->addSelect('description')->get();
    • posts 테이블에서 title 열의 값을 선택하고, 추가적으로 description 열의 값을 선택하여 모든 행을 가져옵니다.
    • SQL: SELECT title, description FROM posts;
  6. DB::table('posts')->where('id', 2)->first();
    • posts 테이블에서 id 값이 2인 첫 번째 행을 가져옵니다.
    • SQL: SELECT * FROM posts WHERE id = 2 LIMIT 1;
  7. DB::table('posts')->where('id', 2)->value('excerpt');
    • posts 테이블에서 id 값이 2인 행의 excerpt 열의 값을 가져옵니다.
    • SQL: SELECT excerpt FROM posts WHERE id = 2 LIMIT 1;
  8. DB::table('posts')->find(1);
    • posts 테이블에서 기본 키가 1인 행을 가져옵니다.
    • SQL: SELECT * FROM posts WHERE id = 1 LIMIT 1;
  9. DB::table('posts')->pluck('title');
    • posts 테이블에서 모든 행의 title 열 값을 배열로 가져옵니다.
  10. DB::table('posts')->pluck('title', 'description');
    • posts 테이블에서 각 행의 title 및 description 열 값을 연관 배열로 가져옵니다. title이 키이고 description이 값입니다.