Query Builder in Laravel 5.8

min read

Day 18 #100DaysOfCode

Hôm nay mình tiếp tục tìm hiểu về Query Builder trong Laravel 5.8. Mình sẽ làm một vài ví dụ để dễ hình dung hơn, để sao này dễ nhớ ::), giờ Laravel ra version 8 rồi ::), mà giờ mình còn mò Laravel 5.8, đúng là đi sau biết bao xa nhĩ, thôi kệ làm từ từ nâng cấp hơn ::)

* Query Builder : sẽ có các cú pháp mà ta có thể lựa chọn để viết câu lệnh truy vấn tới table trong database , bạn có thể xem 2 câu lệnh bên dưới đây

// Non-fluent:
$users = DB::select(['table' => 'users', 'where' => ['type' => 'donor']]);

// Fluent:
$users = DB::table('users')->where('type', 'donor')->get();

Fluent là một query builder, bạn nhìn thấy bên trên giửa Non-fluent và Fluent, có sự khác nhau về cách gọi query đến cơ sở dữ liệu, thông thường Fluent được dùng nhiều xây dựng API cho người dùng, vì nó đơn giản chỉ cần gọi các phương thức mà Fluent cung cấp thôi
Còn nếu viết Non-Fluent mà xây dựng API thì hơi cực xíu, mà cũng đâu sao, đường nào cũng về đích thôi, quan trọng là cách viết của bạn ok là được! 

Okay mình có tạo migration cho product như sau, để hồi test mấy câu lệnh truy vấn thử: 

php artisan make:migration create_products_table --create=products
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('image');
            $table->string('address');
            $table->string('phone');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

Mình chạy lệnh php artisan migrate để tạo table trong database cho ta, sau khi bạn đã có table "products" bạn có thể tạo dữ liệu mẫu bằng factory bạn có thể xem lại hai bài viết dưới đây:

+ Migrations in Laravel 5.8
+ Seeder and Model Factory in Laravel 5.8

Trong truy vấn mình có kết nối join table lại với nhau để so sánh, nên mình cũng có add khóa ngoại user_id đến table "products" , các bạn có thể add vô thêm nghe

Okay, hãy mở file app/Http/controllers/ProductsController.php

+ Sử dụng query-builder

$products = DB::table("products")->get();
dd($products);

Query Builder in Laravel 5.8

Ta có thể truy vấn where để so sánh giá trị tìm kiếm với cơ sở dữ liệu trong database

$product = DB::table("products")->where("email","america84@example.net")->get();
dd($product);

Query Builder in Laravel 5.8

Ta có thể liên kết giữa các table với nhau thông qua phương thức join

$data = DB::table("users")->join("products",function($join){
    $join->on("users.id","=","products.user_id")->where("products.user_id",1)->where("products.email","audie.skiles@example.com");
})->get();
dd($data);

Mình giới thiệu sơ sơ thôi, tí mình sẽ đi tìm từng phương thức trong query-builder xem sao, giờ mình bắt đầu với Raw SQL xem sau:

* RAW SQL : khi sử dụng raw sql, bạn có thể chạy giống như câu lệnh mysql , chứa bắt ký tham số nào bạn muốn truy vấn

       $products = DB::select("select * from products order by id desc");
        dd($products);

      
        $products = DB::select("select * from products where id=:id",['id'=>4]);
        dd($products);

         
        //insert
        DB::insert('insert into products(name,email,image,address,phone,user_id) value(?,?,?,?,?,?)',
        ['Nguyen Van A','xxx@gmail.com','66b02f8c31b7eb7326a18983db520476.jpg','HCM','132432143',1]);
        
        $products = DB::select('select * from products order by id desc');
        dd($products);


        //update
        DB::update('update products set name=? where id=?',['HoanguyenIT',6]);
        //delete 
        DB::delete('delete from product where id=?',[6]);

Đoạn code trên mình dùng Raw SQL, ta có thể dùng truy vấn dữ liệu table, các bạn thấy nó rất quen thuộc đối với ta đúng không, nhưng đồi hỏi bạn phải nhớ đúng chuỗi select query

Còn đối với cách dùng query builder so với raw sql , thì chỉ khác chút thôi cũng không quá xa lạ gì đâu, mình sẽ show ra một vài truy vấn thường dùng nhất cho mọi người xem!

+ Dưới đây là câu lệnh truy vấn table "products" hiện thị tất cả dữ liệu ra cho ta, mình dùng phương thức table() gọi tới table "products" sau đó dùng phương thức select() lấy các cột cần hiện thị

$products = DB::table("products")->select("email","email as email_login")->get();
//or
$products = DB::table("products")->select("email")->addSelect("email as email_login")->get();
dd($products);

+ Sử dụng phương thức where()  trong Query Builder

$products = DB::table("products")->where("email","xxx@gmail.com")->get();
dd($products);

$products = DB::table("products")->where("created_at",">",now()->subDay())->get();
dd($products);

$products = DB::table("products")->where([
                ["email","purdy.treva@example.net"],
                ["created_at",">",now()->subDay()]
        ])->get(); 

$products = DB::table("products")->where("email","purdy.treva@example.net")->where("created_at",">",now()->subDay())->get();

+ Hoặc bạn có thể sử dụng phương thức orWhere() , nó là phương thức thường dùng để so sánh dữ liệu 

//orWhere
$products = DB::table("products")->where("email","purdy.treva@example.net")->orWhere("created_at",">",now()->subDay())->get();
        
$products = DB::table("products")->where("email","purdy.treva@example.net")->orWhere(function($query){
            $query->where("created_at",">",now()->subDay());
        })->get();

+ Phương thức whereBetween() : là phương thức mà ta so sánh giữa các khoảng với nhau, thường ta dùng so sánh từ ngày đến ngày hoặc thống kê mức lương ở một khoảng cho phép nào đó,..v..v..

//whereBetween
         $products = DB::table("products")->whereBetween('id',[3,5])->get();

+ Phương thức whereIn() : giống như trong raw sql như sau : "select * from where id in(4,5)" thì trong phương thức whereIn() sử dụng cú pháp như sau:

$products = DB::table("products")->whereIn('id',[3,5])->get();

tương tự ta cũng có whereNotIn()

 $products = DB::table("products")->whereNotIn('id',[3,5])->get();

+ Phương thức whereRaw() : bạn có thể chèn tham số như sau :whereRaw("id=5") có nghĩa là bạn đang muốn kiếm id=5 trong cơ sở dữ liệu

$products = DB::table("products")->whereRaw('id=5')->get();

+ Phương thức distinct() 

 $products = DB::table("products")->select("user_id")->distinct()->get();

+ Phương thức whereExists()

$products = DB::table("products")->whereExists(function($query){
            $query->select("id")->from('users')->whereRaw('products.user_id=users.id');
        })->get();

+ Phương thức groupBy()

$products = DB::table("products")
                    ->select(\DB::raw('count(user_id) as used_count'))
                    ->groupBy("user_id")
                    ->get();

+ Phương thức orderBy()

$products = DB::table("products")->orderBy("id","desc")->get();

+ Phương thức skip() & take() : giống như bạn đang sử dụng raw sql với truy vấn "select * from products limit 0,4"

$products = DB::table("products")->skip(0)->take(3)->get();

+ Phương thức when() : giống như bạn muốn tìm kiếm theo điều kiện

$email = "ezequiel.schinner@example.org";
        $user_id = 1;
        $products = DB::table("products")->when([$email,$user_id],function($query) use ($email,$user_id){
            return $query->where("user_id",$user_id)->where("email",$email);
        })->get();

+ Phương thức first():

 $product = DB::table('products')->where("id",4)->first();

+ Phương thức max() & min()

 $product = DB::table('products')->max("id");

+ Phương thức count()

 $product = DB::table('products')->where("user_id",1)->count();

+ Phương thức avg(), sum()

 $product = DB::table('products')->where("price",">",1000)->avg('price');

+ Phương thức join()

 $products = DB::table("users")
                ->join("products","users.id","=","products.user_id")
                ->select("users.*","products.name","products.phone")
                ->get();

+ Phương thức insertGetId() : cái này rất hay nhé , bạn thêm một dữ liệu vào , nếu thành công sẽ return về id bạn mới thêm vào

 $id = DB::table("products")
               ->insertGetId([
                    "name"=>"Hoa Thanh",
                    "email"=>"xxx123@gmail.com",
                    "phone"=>"12133213333",
                    "address"=>"HCM",
                    "image"=>"avatar.jpg",
                    "user_id"=>1
               ]);

+ Phương thức insert() : bạn có thể thêm nhiều dữ liệu cho một thao tác nhé, bạn phải đưa dữ liệu vào một mảng rồi insert vào

 $products = DB::table("products")
               ->insert([
                   [
                    "name"=>"Hoa Thanh 1",
                    "email"=>"xxx123324@gmail.com",
                    "phone"=>"12133213333",
                    "address"=>"HCM",
                    "image"=>"avatar1.jpg",
                    "user_id"=>1
                   ],
                   [
                    "name"=>"Hoa Thanh 2",
                    "email"=>"xxx12354354435e@gmail.com",
                    "phone"=>"654675477",
                    "address"=>"HCM",
                    "image"=>"avatar2.jpg",
                    "user_id"=>1
                     ]
               ]);

+ Phương thức update()

 $products = DB::table("products")->where("id",1)->update(["name"=>"Nguyễn Văn A"]);

+ Phương thức delete()

 $products = DB::table("products")->where("id",">",7)->delete();

Okay mình chỉ tìm hiểu được bao nhiêu, chắc mình phải tìm hiểu thêm nửa vì còn nhiều điều chưa biết tới, các bạn có thể lên mạng search và xem thêm nghe! 

x

Ủng hộ tôi bằng cách click vào quảng cáo. Để tôi có kinh phí tiếp tục phát triển Website!(Support me by clicking on the ad. Let me have the money to continue developing the Website!)