


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











Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

When developing websites using CraftCMS, you often encounter resource file caching problems, especially when you frequently update CSS and JavaScript files, old versions of files may still be cached by the browser, causing users to not see the latest changes in time. This problem not only affects the user experience, but also increases the difficulty of development and debugging. Recently, I encountered similar troubles in my project, and after some exploration, I found the plugin wiejeben/craft-laravel-mix, which perfectly solved my caching problem.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.
