search
HomeBackend DevelopmentPHP TutorialLaravel framework database CURD operation, coherent operation summary, laravelcurd_PHP tutorial

Laravel framework database CURD operation and coherent operation summary, laravelcurd

1. Selects

Retrieve all rows in the table

Copy code The code is as follows:

$users = DB::table('users')->get();
foreach ($users as $user)
{
var_dump($user->name);
}

Retrieve a single row from the table

Copy code The code is as follows:

$user = DB::table('users')->where('name', 'John')->first();
var_dump($user->name);

Retrieve rows for a single column
Copy code The code is as follows:

$name = DB::table('users')->where('name', 'John')->pluck('name');

Retrieve a list of column values
Copy code The code is as follows:

$roles = DB::table('roles')->lists('title');

This method will return an array title. You can also specify a custom key column to return in the array
Copy code The code is as follows:

$roles = DB::table('roles')->lists('title', 'name');

Specify a Select clause
Copy code The code is as follows:

$users = DB::table('users')->select('name', 'email')->get();
​$users = DB::table('users')->distinct()->get();
​$users = DB::table('users')->select('name as user_name')->get();

Select clause added to an existing query $query = DB::table('users')->select('name');

Copy code The code is as follows:

$users = $query->addSelect('age')->get();

where

Copy code The code is as follows:

$users = DB::table('users')->where('votes', '>', 100)->get();

OR

Copy code The code is as follows:

$users = DB::table('users')->where('votes', '>', 100)->orWhere('name', 'John')->get();

Where Between

Copy code The code is as follows:

$users = DB::table('users')->whereBetween('votes', array(1, 100))->get();

Where Not Between

Copy code The code is as follows:

$users = DB::table('users')->whereNotBetween('votes', array(1, 100))->get();

Where In With An Array

Copy code The code is as follows:

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();
$users = DB::table('users')->whereNotIn('id', array(1, 2, 3))->get();

Using Where Null To Find Records With Unset Values

Copy code The code is as follows:

$users = DB::table('users')->whereNull('updated_at')->get();

Order By, Group By, And Having

Copy code The code is as follows:

$users = DB::table('users')->orderBy('name', 'desc')->groupBy('count')->having('count', '>', 100) ->get();

Offset & Limit

Copy code The code is as follows:

$users = DB::table('users')->skip(10)->take(5)->get();

2. Connection

Joins

The query builder can also be used to write join statements. Take a look at the example below:

Basic Join Statement

Copy code The code is as follows:

DB::table('users')
  ->join('contacts', 'users.id', '=', 'contacts.user_id')
  ->join('orders', 'users.id', '=', 'orders.user_id')
  ->select('users.id', 'contacts.phone', 'orders.price')
  ->get();

左连接语句

复制代码 代码如下:

DB::table('users')
  ->leftJoin('posts', 'users.id', '=', 'posts.user_id')
  ->get();
  DB::table('users')
  ->join('contacts', function($join)
  {
  $join->on('users.id', '=', 'contacts.user_id')->orOn(...);
  })
  ->get();
  DB::table('users')
  ->join('contacts', function($join)
  {
  $join->on('users.id', '=', 'contacts.user_id')
  ->where('contacts.user_id', '>', 5);
  })
  ->get();

三、分组

  有时候,您可能需要创建更高级的where子句,如“存在”或嵌套参数分组。Laravel query builder可以处理这些:

复制代码 代码如下:

DB::table('users')
->where('name', '=', 'John')
->orWhere(function($query)
{
$query->where('votes', '>', 100)
->where('title', '', 'Admin');
})
->get();

  上面的查询将产生以下SQL:
复制代码 代码如下:

  select * from users where name = 'John' or (votes > 100 and title
'Admin')
  Exists Statements
  DB::table('users')
  ->whereExists(function($query)
  {
  $query->select(DB::raw(1))
  ->from('orders')
  ->whereRaw('orders.user_id = users.id');
  })
  ->get();

上面的查询将产生以下SQL:

复制代码 代码如下:

select * from userswhere exists (
select 1 from orders where orders.user_id = users.id
)

四、聚合

查询构建器还提供了各种聚合方法,如统计,马克斯,min,avg和总和。

Using Aggregate Methods

复制代码 代码如下:

$users = DB::table('users')->count();
$price = DB::table('orders')->max('price');
$price = DB::table('orders')->min('price');
$price = DB::table('orders')->avg('price');
$total = DB::table('users')->sum('votes');

Raw Expressions

有时您可能需要使用一个原始表达式的查询。这些表达式将注入的查询字符串,所以小心不要创建任何SQL注入点!创建一个原始表达式,可以使用DB:rawmethod:

Using A Raw Expression

复制代码 代码如下:

$users = DB::table('users')
->select(DB::raw('count(*) as user_count, status'))
->where('status', '', 1)
->groupBy('status')
->get();

递增或递减一个列的值

复制代码 代码如下:

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, array('name' => 'John'));

Inserts

将记录插入表

复制代码 代码如下:

DB::table('users')->insert(
array('email' => 'john@example.com', 'votes' => 0)
);

将记录插入表自动增加的ID

如果表,有一个自动递增的id字段使用insertGetId插入一个记录和检索id:

复制代码 代码如下:

$id = DB::table('users')->insertGetId(
array('email' => 'john@example.com', 'votes' => 0)
);

Note: When using the PostgreSQL insertGetId method it is expected that the auto-incrementing column will be named "id".

Multiple records are inserted into the table

Copy code The code is as follows:

DB::table('users')->insert(array(
array('email' => 'taylor@example.com', 'votes' => 0),
array('email' => 'dayle@example.com', 'votes' => 0),
));

4. Updates

Update records in a table

Copy code The code is as follows:

DB::table('users')
->where('id', 1)
->update(array('votes' => 1));

5. Deletes

Delete records in table

Copy code The code is as follows:

DB::table('users')->where('votes', 'delete();

Delete all records in the table

Copy code The code is as follows:

DB::table('users')->delete();

Delete a table
Copy code The code is as follows:

DB::table('users')->truncate();

6. Unions

The query builder also provides a quick way to "union" two queries:

Copy code The code is as follows:

​$first = DB::table('users')->whereNull('first_name');
​$users =
DB::table('users')->whereNull('last_name')->union($first)->get();

The unionAll method can also be used, with the same method signature.

Pessimistic Locking

The query builder includes some "pessimistic locking" features to help you with your SELECT statements. Run the SELECT statement "Shared Lock", you can use the sharedLock method to query:

Copy code The code is as follows:

DB::table('users')->where('votes', '>',
100)->sharedLock()->get();

To update the "lock" in a SELECT statement, you can query using the lockForUpdate method:
Copy code The code is as follows:

DB::table('users')->where('votes', '>', 100)->lockForUpdate()->get();

7. Cache query

You can easily cache the results of a query using mnemonics:

Copy code The code is as follows:

$users = DB::table('users')->remember(10)->get();

In this example, the results of the query will be cached for ten minutes. When query results are cached, they are not run against the database and the results will be loaded from the default cache driver specified by your application. ​If you are using a driver that supports caching, you can also add tags to cache:
Copy code The code is as follows:

$users = DB::table('users')->cacheTags(array('people', 'authors'))->remember(10)->get();

php_laravel framework

280907494 Development group, there are many people doing this in the group.

PHP laravel framework, the first access entrance is normal, and an error is reported after refreshing

Turn on debug to see detailed errors

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/874112.htmlTechArticleLaravel framework database CURD operation, summary of coherent operation, laravelcurd 1. Selects retrieval table all rows copy code code is as follows : $users = DB::table('users')-get(); foreach ($u...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)