การใช้งานฐานข้อมูล (อิงจากส่วนประกอบฐานข้อมูลของ Laravel)
การดึงข้อมูลทั้งหมด
<?php
namespace app\controller;
use support\Request;
use support\Db;
class UserController
{
public function all(Request $request)
{
$users = Db::table('users')->get();
return view('user/all', ['users' => $users]);
}
}
การดึงข้อมูลคอลัมน์ที่กำหนด
$users = Db::table('user')->select('name', 'email as user_email')->get();
การดึงข้อมูลแค่หนึ่งแถว
$user = Db::table('users')->where('name', 'John')->first();
การดึงข้อมูลแค่หนึ่งคอลัมน์
$titles = Db::table('roles')->pluck('title');
ใช้ค่าของฟิลด์ id เป็นดัชนี
$roles = Db::table('roles')->pluck('title', 'id');
foreach ($roles as $id => $title) {
echo $title;
}
การดึงค่าคนเดียว (ฟิลด์)
$email = Db::table('users')->where('name', 'John')->value('email');
การตัดข้อมูลซ้ำ
$email = Db::table('user')->select('nickname')->distinct()->get();
การแบ่งผลลัพธ์
หากคุณต้องการจัดการกับบันทึกฐานข้อมูลหลายพันรายการ การอ่านข้อมูลทั้งหมดในครั้งเดียวอาจใช้เวลานานและอาจทำให้หน่วยความจำเกินขีดจำกัด ในกรณีนี้คุณสามารถใช้วิธี chunkById เพื่อรับชุดผลลัพธ์ขนาดเล็กในแต่ละครั้งและส่งต่อให้ฟังก์ชัน closure เพื่อจัดการ ตัวอย่างเช่น เราสามารถแบ่งข้อมูลทั้งหมดในตาราง users เป็นการจัดการ 100 รายการในแต่ละครั้ง:
Db::table('users')->orderBy('id')->chunkById(100, function ($users) {
foreach ($users as $user) {
//
}
});
คุณสามารถหยุดการดึงผลลัพธ์ต่อได้โดยการคืนค่า false ในฟังก์ชัน closure
Db::table('users')->orderBy('id')->chunkById(100, function ($users) {
// Process the records...
return false;
});
หมายเหตุ: อย่าลบข้อมูลภายในฟังก์ชัน callback เพราะอาจส่งผลให้บันทึกบางรายการไม่รวมอยู่ในชุดผลลัพธ์
การรวม
ตัวสร้างคำสั่งค้นหายังมีวิธีการรวมที่หลากหลาย เช่น count, max, min, avg, sum เป็นต้น
$users = Db::table('users')->count();
$price = Db::table('orders')->max('price');
$price = Db::table('orders')->where('finalized', 1)->avg('price');
การตรวจสอบว่ามีบันทึกหรือไม่
return Db::table('orders')->where('finalized', 1)->exists();
return Db::table('orders')->where('finalized', 1)->doesntExist();
การแสดงดิบ
ต้นแบบ
selectRaw($expression, $bindings = [])
บางครั้งคุณอาจต้องการใช้การแสดงดิบในคำค้น คุณสามารถใช้ selectRaw()
เพื่อสร้างการแสดงดิบ:
$orders = Db::table('orders')
->selectRaw('price * ? as price_with_tax', [1.0825])
->get();
นอกจากนี้ยังมีวิธีการแสดงดิบอื่น ๆ เช่น whereRaw()
orWhereRaw()
havingRaw()
orHavingRaw()
orderByRaw()
groupByRaw()
Db::raw($value)
ยังใช้สำหรับสร้างการแสดงดิบ แต่ไม่มีฟังก์ชันการผูกพารามิเตอร์ ให้ระมัดระวังกับปัญหา SQL injection เมื่อใช้.
$orders = Db::table('orders')
->select('department', Db::raw('SUM(price) as total_sales'))
->groupBy('department')
->havingRaw('SUM(price) > ?', [2500])
->get();
คำสั่ง Join
// join
$users = Db::table('users')
->join('contacts', 'users.id', '=', 'contacts.user_id')
->join('orders', 'users.id', '=', 'orders.user_id')
->select('users.*', 'contacts.phone', 'orders.price')
->get();
// leftJoin
$users = Db::table('users')
->leftJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
// rightJoin
$users = Db::table('users')
->rightJoin('posts', 'users.id', '=', 'posts.user_id')
->get();
// crossJoin
$users = Db::table('sizes')
->crossJoin('colors')
->get();
คำสั่ง Union
$first = Db::table('users')
->whereNull('first_name');
$users = Db::table('users')
->whereNull('last_name')
->union($first)
->get();
คำสั่ง Where
ต้นแบบ
where($column, $operator = null, $value = null)
พารามิเตอร์แรกเป็นชื่อคอลัมน์ พารามิเตอร์ที่สองเป็นตัวดำเนินการใด ๆ ที่ระบบฐานข้อมูลรองรับ และพารามิเตอร์ที่สามคือค่าที่จะเปรียบเทียบของคอลัมน์
$users = Db::table('users')->where('votes', '=', 100)->get();
// เมื่อทำการเปรียบเทียบด้วยเท่ากัน สามารถละพารามิเตอร์ได้ ดังนั้นคำสั่งนี้จึงมีผลเหมือนกับคำสั่งก่อนหน้า
$users = Db::table('users')->where('votes', 100)->get();
$users = Db::table('users')
->where('votes', '>=', 100)
->get();
$users = Db::table('users')
->where('votes', '<>', 100)
->get();
$users = Db::table('users')
->where('name', 'like', 'T%')
->get();
คุณยังสามารถส่งอาร์เรย์เงื่อนไขไปยังฟังก์ชัน where ได้:
$users = Db::table('users')->where([
['status', '=', '1'],
['subscribed', '<>', '1'],
])->get();
orWhere ตัวรับพารามิเตอร์เช่นเดียวกับ where:
$users = Db::table('users')
->where('votes', '>', 100)
->orWhere('name', 'John')
->get();
คุณสามารถส่งฟังก์ชันปิดให้กับ orWhere เป็นพารามิเตอร์แรก:
// SQL: select * from users where votes > 100 or (name = 'Abigail' and votes > 50)
$users = Db::table('users')
->where('votes', '>', 100)
->orWhere(function($query) {
$query->where('name', 'Abigail')
->where('votes', '>', 50);
})
->get();
whereBetween / orWhereBetween วิธีใช้ตรวจสอบว่าค่าฟิลด์อยู่ระหว่างค่าทั้งสองที่กำหนด:
$users = Db::table('users')
->whereBetween('votes', [1, 100])
->get();
whereNotBetween / orWhereNotBetween วิธีใช้ตรวจสอบว่าค่าฟิลด์อยู่นอกค่าทั้งสองที่กำหนด:
$users = Db::table('users')
->whereNotBetween('votes', [1, 100])
->get();
whereIn / whereNotIn / orWhereIn / orWhereNotIn วิธีใช้ตรวจสอบว่าค่าฟิลด์ต้องอยู่ในอาร์เรย์ที่กำหนด:
$users = Db::table('users')
->whereIn('id', [1, 2, 3])
->get();
whereNull / whereNotNull / orWhereNull / orWhereNotNull วิธีใช้ตรวจสอบว่าฟิลด์ที่กำหนดต้องเป็น NULL:
$users = Db::table('users')
->whereNull('updated_at')
->get();
whereNotNull วิธีใช้ตรวจสอบว่าฟิลด์ที่กำหนดต้องไม่เป็น NULL:
$users = Db::table('users')
->whereNotNull('updated_at')
->get();
whereDate / whereMonth / whereDay / whereYear / whereTime วิธีใช้เพื่อเปรียบเทียบค่าฟิลด์กับวันที่ที่กำหนด:
$users = Db::table('users')
->whereDate('created_at', '2016-12-31')
->get();
whereColumn / orWhereColumn วิธีใช้เพื่อเปรียบเทียบค่าฟิลด์สองค่าว่ามีค่าตรงกันหรือไม่:
$users = Db::table('users')
->whereColumn('first_name', 'last_name')
->get();
// คุณยังสามารถระบุการเปรียบเทียบได้
$users = Db::table('users')
->whereColumn('updated_at', '>', 'created_at')
->get();
// whereColumn ยังสามารถส่งอาร์เรย์
$users = Db::table('users')
->whereColumn([
['first_name', '=', 'last_name'],
['updated_at', '>', 'created_at'],
])->get();
การจัดกลุ่มพารามิเตอร์
// select * from users where name = 'John' and (votes > 100 or title = 'Admin')
$users = Db::table('users')
->where('name', '=', 'John')
->where(function ($query) {
$query->where('votes', '>', 100)
->orWhere('title', '=', 'Admin');
})
->get();
whereExists
// select * from users where exists ( select 1 from orders where orders.user_id = users.id )
$users = Db::table('users')
->whereExists(function ($query) {
$query->select(Db::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
orderBy
$users = Db::table('users')
->orderBy('name', 'desc')
->get();
การสุ่มเรียง
$randomUser = Db::table('users')
->inRandomOrder()
->first();
การสั่งเรียงแบบสุ่มอาจมีผลกระทบต่อประสิทธิภาพของเซิร์ฟเวอร์ ไม่แนะนำให้ใช้
groupBy / having
$users = Db::table('users')
->groupBy('account_id')
->having('account_id', '>', 100)
->get();
// คุณสามารถส่งพารามิเตอร์หลายค่าไปยังฟังก์ชัน groupBy
$users = Db::table('users')
->groupBy('first_name', 'status')
->having('account_id', '>', 100)
->get();
offset / limit
$users = Db::table('users')
->offset(10)
->limit(5)
->get();
การแทรก
บันทึกเดี่ยว
Db::table('users')->insert(
['email' => 'john@example.com', 'votes' => 0]
);
บันทึกหลายรายการ
Db::table('users')->insert([
['email' => 'taylor@example.com', 'votes' => 0],
['email' => 'dayle@example.com', 'votes' => 0]
]);
การเพิ่ม ID อัตโนมัติ
$id = Db::table('users')->insertGetId(
['email' => 'john@example.com', 'votes' => 0]
);
หมายเหตุ: เมื่อใช้ PostgreSQL วิธี insertGetId จะตั้งค่า id เป็นชื่อฟิลด์ที่เพิ่มอัตโนมัติเป็นค่าเริ่มต้น หากคุณต้องการดึง ID จาก "ลำดับ" อื่น ให้ส่งชื่อฟิลด์เป็นพารามิเตอร์ที่สองไปยังวิธี insertGetId
การอัปเดต
$affected = Db::table('users')
->where('id', 1)
->update(['votes' => 1]);
การอัปเดตหรือเพิ่ม
บางครั้งคุณอาจต้องการอัปเดตบันทึกที่มีอยู่ในฐานข้อมูล หากไม่มีบันทึกที่ตรงกันให้สร้าง:
Db::table('users')
->updateOrInsert(
['email' => 'john@example.com', 'name' => 'John'],
['votes' => '2']
);
วิธี updateOrInsert จะพยายามค้นหาบันทึกในฐานข้อมูลที่ตรงกันโดยใช้คีย์และค่าจากพารามิเตอร์แรก หากบันทึกมีอยู่จะอัปเดตด้วยค่าจากพารามิเตอร์ที่สอง หากไม่พบบันทึกใหม่จะถูกเพิ่ม บันทึกใหม่คือข้อมูลที่รวมจากสองอาร์เรย์
เพิ่มและลด
วิธีทั้งสองนี้รับพารามิเตอร์ขั้นต่ำหนึ่งรายการ: คอลัมน์ที่ต้องการปรับปรุง พารามิเตอร์ที่สองเป็นค่าเริ่มต้นที่จะควบคุมการเพิ่มหรือลดของคอลัมน์:
Db::table('users')->increment('votes');
Db::table('users')->increment('votes', 5);
Db::table('users')->decrement('votes');
Db::table('users')->decrement('votes', 5);
คุณยังสามารถระบุฟิลด์ที่ต้องการอัปเดตในระหว่างกระบวนการ:
Db::table('users')->increment('votes', 1, ['name' => 'John']);
การลบ
Db::table('users')->delete();
Db::table('users')->where('votes', '>', 100)->delete();
หากคุณต้องการล้างตารางทั้งหมด คุณสามารถใช้วิธี truncate ซึ่งจะลบบรรทัดทั้งหมดและรีเซ็ต ID ที่เพิ่มอัตโนมัติเป็นศูนย์:
Db::table('users')->truncate();
ธุรกรรม
ล็อกแบบพยากรณ์
ตัวสร้างคำสั่งค้นหายังมีฟังก์ชันที่ช่วยให้คุณใช้ "การล็อกแบบพยากรณ์" กับคำสั่ง select ได้ หากต้องการใช้ "การล็อกแบบแชร์" ในคำค้น คุณสามารถใช้ sharedLock วิธีนี้จะป้องกันไม่ให้ข้อมูลที่เลือกถูกแก้ไขจนกว่าธุรกรรมจะถูกส่ง:
Db::table('users')->where('votes', '>', 100)->sharedLock()->get();
หรือคุณสามารถใช้ lockForUpdate วิธีใช้ "ล็อกสำหรับอัปเดต" ป้องกันไม่ให้แถวถูกแก้ไขหรือเลือกโดยการล็อกแบบแชร์อื่น ๆ:
Db::table('users')->where('votes', '>', 100)->lockForUpdate()->get();
การดีบัก
คุณสามารถใช้ dd หรือ dump เพื่อแสดงผลลัพธ์การค้นหาหรือคำสั่ง SQL การใช้ dd จะแสดงข้อมูลการดีบักและหยุดการประมวลผลคำขอ ขณะที่ dump จะแสดงข้อมูลการดีบักเช่นกัน แต่จะไม่หยุดการประมวลผลคำขอ:
Db::table('users')->where('votes', '>', 100)->dd();
Db::table('users')->where('votes', '>', 100)->dump();
หมายเหตุ
การดีบักต้องติดตั้งsymfony/var-dumper
, คำสั่งคือcomposer require symfony/var-dumper