Hướng dẫn Multiple Where Laravel Eloquent

  • October 20, 2022
  • 504

Hôm nay, chúng ta cùng tìm hiểu các cách sử dụng multiple where khi làm việc với laravel framework từ đơn giản đến phức tạp nhé.

Laravel Eloquent multiple where

1. Muitiple where and

Tạo một query lấy ra tất cả các users có username là test và trạng thái active là 1


SELECT * FROM users where username = 'test' AND active = 1;

Câu truy vấn trên được viết trong laravel theo các cách sau


// Cách 1
$users = User::where([
       'username' => 'test',
       'active' => 1,
])->get();

// Cách 2
$users = User::where('username', 'test')->where('active', 1)->get();

2. Muitiple where and, where or

Tạo một query lấy tất cả các users có first_name hoặc last_name là test


// Mysql query
SELECT * FROM users where first_name = 'test' OR last_name = 'test';

// Laravel eloquent
$users = User::where('first_name', 'test')
->orWhere('first_name', 'test')->get();

3. Where multilpe operator

Câu query sử dụng multiple operator, lấy tất cả các users có first_name chứa từ test, active khác 0, hoặc first_name là fixed


// Mysql query
SELECT * FROM users where first_name like '%test%' AND active != 0 OR first_name = 'fixed';

// Laravel eloquent
$users = User::where([
    ['first_name', 'like', 'test'],
    ['active', '<>', 0],
    ['first_name', '=', 'fixed'],
])->get();

// Where multiple operator
$query->where([
    ['column_1', '=', 'value_1'],
    ['column_2', '<>', 'value_2'],
    [COLUMN, OPERATOR, VALUE],
    ...
])

4. Conditions using Anonymous Function


// Mysql query
SELECT * FROM users
WHERE column1 = value1 
AND (column2 = value2 or column3 = value3) 
AND (column4 = value4 and column5 = value5)

// Laravel eloquent
$value2 = 'value2';
$value3 = 'value3';
$value4 = 'value4';
$value5 = 'value5';
$users = User::where('column1', '=', 'value1')
            ->where(function($query) use ($value2, $value3) {
                $query->where('column2', $value2)
                ->orWhere('column3', $value3);
            })
            ->where(function($query2) use ($value4, $value5) {
                $query2->where('column4', $value4)
                ->where('column5', $value5);
            })->get();

5. Mutilple where with relation

Lấy ra tất cả các sản phẩm được public có title bằng test hoặc các sản phẩm được public có tag name là test


$title = 'test';
$query = Product::where([
        'published' => 1,
        ['title', 'LIKE', '%' . $title . '%']
    ])->orWhere(function($query) use ($title) {
    $query->where([
            'published' => 1
        ])
        ->whereHas('tags', function (Builder $query) use ($title) {
            $query->where('name', 'like', '%' . $title . '%');
        });
    })
    ->get();

6. Mutilple where with sum relation

Lấy ra tất cả các sản phẩm còn hàng


// Cần dùng having mà không thể dùng where
// do where không thể thực hiện với các hàm tính tổng
// một sản phẩm có thể có nhiều items, is_stock lưu số hàng còn Product::withSum('items', 'in_stock') ->having('items_sum_in_stock', '>', 0);

7. Use where on withCount, withSum

Lấy ra tổng số tiền người dùng mua 1 sản phẩm


Product::withSum('transactions as sum_price' , 'price');

Lấy ra tổng số tiền có thuế và phí ship của một sản phẩm có trạng thái đơn hàng là 2


Product::withCount([
        'transactions AS total_price' => function ($query) {
            $query->selectDB::raw("SUM(non_taxed_price + total_taxed + shipping_fee) as total"))
                ->where('status', 2);
        }
]);

Lấy ra tổng số tiền người dùng mua 1 sản phẩm mà trạng thái đơn hàng = 2


Product::withCount([
        'transactions AS sum_price' => function ($query) {
                $query->select(DB::raw("SUM(price) as total"))
                ->where('status', 2);
         }
]);

Lấy ra tổng số người dùng có trạng thái đơn hàng = 2


Product::withCount([
     'transactions AS total_transaction' => function ($query) {
            $query->select(DB::raw("COUNT(DISTINCT(user_id))"))
            ->where('status', 2);
      }
]);

Lấy ra tổng số transactions của 1 sản phẩm


Product::withCount('transactions as total_transaction');

Lấy ra tổng số transactions có status = 2 của 1 sản phẩm


Product::withCount([
    'transactions AS total_transaction' => function ($query) {
           $query->where('status', 2);
     }
]);

8. Order and withSum sub relation

Sắp xếp các item của sản phẩm theo thứ tự item còn nhiều hàng lên trước và lấy tổng số transaction của item đó.


Product::with(['items' => function ($q) {
            $q->withSum('itemTransactions as sum_stock' , 'stock')
            ->orderBy('in_stock', 'DESC');
      }]);