[laravel 5.4] Database Query Builder

29 ส.ค. 2017 , 10,115 Views   , หมวดหมู่ Laravel ทุกหมวดหมู่ โค๊ดดิ้ง   , ป้ายกำกับ:


Retrieving Results

ดึงข้อมูลทั้งหมด

ข้อมูลออกมาเป็น array

ดึงข้อมูลมาแถวเดียว

ดึงมาเฉพาะ column ที่ต้องการ

ดึง column เดียวออกมาทั้งหมด

ข้อมูลออกมาเป็น array

ระบุค่า index,value ของ array ที่จะให้ออกมาได้

Chunking Results

คือการแบ่ง Query ออกเป็นช่วงๆ จะช่วยประหยัดหน่วยความจำ(memory) เมื่อทำงานกับชุดผลลัพธ์ขนาดใหญ่ ตัวอย่างข้างล่างคือ ระบบจะ query ครั้งล่ะ 200 rows ไปจนกว่าจะสิ้นสุด

สามารถหยุดการ query ได้ด้วย  return false

Aggregates

สามารถใช้  countmaxminavg, และsum ตามตัวอย่างด้านล่าง

สามารถใช้ร่วมกับฟังค์ชันอื่นๆได้

Selects

เลือกเฉพาะ column ที่ต้องการ

distinct

addSelect

Raw Expressions

บางครั้งหากต้องการแทรกคำสั่ง SQL เข้าไป สามารถใช้  DB::raw  ได้

Joins

Inner Join

Left Join

Cross Join

Advanced Join

Unions

Where

Simple Where Clauses

Or Statements

Additional Where Clauses

whereBetween

whereNotBetween

whereIn / whereNotIn

whereIn

whereNotIn

whereNull / whereNotNull

whereNull

whereNotNull

whereDate / whereMonth / whereDay / whereYear

whereDate

whereMonth

whereDay

whereYear

whereColumn

ตรวจสอบเงื่อนไขระหว่ง column

สามารถใช้ Comparison operator ได้

ใส่ได้หลาย Conditions

Parameter Grouping

หากต้องการส่ง parameter เข้าไป

Where Exists

JSON Where Clauses

Laravel also supports querying JSON column types on databases that provide support for JSON column types.

Conditional Clauses

ตรวจสอบค่าของตัวแปล หากมีค่าก็ให้ทำตาม condition

หาก role มีค่า คำส่ง SQL ก็จะเป็น

หาก role ไม่มีค่าหรือเป็นค่าว่าง คำสั่ง SQL ก็จะเป็น

เงื่อนไขข้างล่างหาก sortBy ไม่มีค่าหรือมีค่า null ก็จะทำตามเงื่อนไขที่สอง

คำสั่ง SQL ก็จะออกมาเป็น

Ordering, Grouping, Limit, & Offset

orderBy

latest / oldest

latest คือล่าสุด(desc) oldest  คือเก่าสุด(asc) โดยค่าเริ่มต้นระบบจะจัดเรียงตาม  created_at  หากต้องการจัดเรียงตาม column อื่นสามารถระบุชื่อ column ได้

ระบุชื่อ column

inRandomOrder

ระบบจะ Sort แบบสุ่มมา

groupBy / having / havingRaw

havingRaw

skip / take

หรือใช้โค๊ดด้านล่างก็ได้เช่นกัน

Inserts

หลายๆเรคคอร์ด

Auto-Incrementing IDs

หาก id ในตารางเป็นแบบ auto-incrementing id สามารถใช้  insertGetId พร้อมทั้ง รีเทรินค่าเป็น ID ที่ Insert ด้วย

Updates

Updating JSON Columns

Increment & Decrement

การเพิ่มและลดค่า

สามารถใส่ column และ value เพิ่มเติมเพื่ออัพเดทได้

Deletes

หากต้องการลบข้อมูลทั้งหมดและรีเซ็นค่า ID ที่เป็น auto-incrementing ให้เป็น 0 สามารถใช้ truncate  ได้

Pessimistic Locking

The query builder also includes a few functions to help you do “pessimistic locking” on your selectstatements. To run the statement with a “shared lock”, you may use the sharedLock method on a query. A shared lock prevents the selected rows from being modified until your transaction commits:

Alternatively, you may use the lockForUpdate method. A “for update” lock prevents the rows from being modified or from being selected with another shared lock:

 

ที่มา

https://laravel.com/docs/5.4/queries


ป้ายกำกับ: