


Laravel learning - sample code sharing for database operations and query constructors
Recently, the editor is studying what is known as the best framework in the world – Laravel. In fact, learning framework is also the idea of learning framework! I want to record some of my experiences in laravel learning in my blog. Everyone is welcome to follow my other Github blogs and short books to communicate with each other!
Version: Laravel 5.2
Database: mysql 5.7
php:php7.1
Database operationandQueryConstructor
There are two ways to perform database operations in Laravel, one One is to use the static method of the \DB
appearance object to directly execute the sql query, and the other is to use the static method of the Model class (actually also the implementation of Facade, using the static access method to access the Model, which is used internally callStatic
The magic method proxies access to the member method
Query operation
Use sql statement to execute the select query operation
#$results = DB::select('select * from users where id = ?', [1]);foreach ($results as $res) { echo $res->name; }
The return result is. Array, each value in the array is a StdClass
object.
You can also use named binding. It is recommended to use this method, which is more clear.
$results = DB::select('select * from users where id = :id', ['id' => 1]);
Get all the objects from the data table. Data column
#$users = DB::table('users')->get(); foreach ($users as $user) { var_dump($user->name); }
Query a single row/column from the table
Use the first method to return a single row of data. This method returns a stdClass object
$user = DB::table('users')->where('name', 'John')->first(); echo $user->name;
If you only need one column value, you can use the value method to directly obtain the value of a single column
$email = DB::table('users')->where('name', 'John')->value('email');
Search the data column in blocks from the data table
This method is used for operations with a large amount of data in the data table. Take out a part of the result set at a time, use the closure function to process it, and then process the next part. This command is generally used in the Artisan command line program to process large amounts of data
DB::table('users')->chunk(100, function($users){ foreach ($users as $user) { // } });
In the closure function, if it returns#. ##false, will stop subsequent processing
titles in the role table. Field value
$titles = DB::table('roles')->pluck('title');foreach ($titles as $title) { echo $title; }
pluck function here has two parameters
Collection pluck( string $column, string|null $key = null)
$roles = DB::table('roles')->pluck('title', 'name');foreach ($roles as $name => $title) { echo $title; }
count, max, min, avg, sum, etc.
$users = DB::table('users')->count(); $price = DB::table('orders')->max('price'); $price = DB::table('orders')->where('finalized', 1)->avg('price');
#
$users = DB::table('users')->select('name', 'email as user_email')->get();
$query = DB::table('users')->select('name');$users = $query->addSelect('age')->get();
#
$users = DB::table('users')->distinct()->get();
DB::raw method to inject the required sql fragment into the query, but It is highly not recommended to use this method. If used incorrectly, sql injection may occur.
$users = DB::table('users') ->select(DB::raw('count(*) as user_count, status')) ->where('status', '<>', 1) ->groupBy('status') ->get();
$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();
#Use the leftJoin method to perform the left join operation. The parameters are the same as join $users =
DB::table('users') ->leftJoin('posts', 'users.id', '=', 'posts.user_id') ->get();
<p style="margin-top: 7px;">DB::table('users')<br/> ->join('contacts', function ($join) {<br/> $join->on('users.id', '=', 'contacts.user_id')->orOn(...);<br/> })<br/> ->get();<br/></p>
DB::table('users') ->join('contacts', function ($join) { $join->on('users.id', '=', 'contacts.user_id') ->where('contacts.user_id', '>', 5); }) ->get();
$first = DB::table('users') ->whereNull('first_name'); $users = DB::table('users') ->whereNull('last_name') ->union($first) ->get();
unionAll method can also be used, with the same parameters as union.
$users = DB::table('users')->where('votes', '=', 100)->get(); $users = DB::table('users')->where('votes', 100)->get();
The above is the detailed content of Laravel learning - sample code sharing for database operations and query constructors. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Method for obtaining the return code when Laravel email sending fails. When using Laravel to develop applications, you often encounter situations where you need to send verification codes. And in reality...

The method of handling Laravel's email failure to send verification code is to use Laravel...

How to implement the table function of custom click to add data in dcatadmin (laravel-admin) When using dcat...

The impact of sharing of Redis connections in Laravel framework and select methods When using Laravel framework and Redis, developers may encounter a problem: through configuration...

Custom tenant database connection in Laravel multi-tenant extension package stancl/tenancy When building multi-tenant applications using Laravel multi-tenant extension package stancl/tenancy,...

LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->

How to check the validity of Redis connections in Laravel6 projects is a common problem, especially when projects rely on Redis for business processing. The following is...

A problem of duplicate class definition during Laravel database migration occurs. When using the Laravel framework for database migration, developers may encounter "classes have been used...
