search
HomePHP FrameworkLaravelWhat database does laravel support?

What database does laravel support?

Feb 14, 2022 pm 03:38 PM
laraveldatabase

laravel supports four databases: 1. MySQL, a relational database management system; 2. PostgreSQL, an "object-relational" database management system; 3. SQLite, a lightweight relational database Management system; 4. SQL Server, a relational database management system.

What database does laravel support?

The operating environment of this tutorial: Windows 7 system, Laravel 6 version, Dell G3 computer.

Laravel supports native SQL queries, fluent query builders and Eloquent ORM. These operations make interacting with the database very simple in various database backends.

Currently Laravel supports the following four databases:

  • MySQL 5.7: a relational database management system developed by the Swedish MySQL AB company and belongs to Products of Oracle.

  • PostgreSQL 9.6: A free software object-relational database management system with very complete features. It is an object-relational database management system based on POSTGRES, version 4.2, developed by the Department of Computer Science at the University of California. Database management system.

  • SQLite 3.8.8: A lightweight database, an ACID-compliant relational database management system, contained in a relatively small C library.

  • SQL Server 2017: A relational database management system launched by Microsoft

Configuration

The database configuration file is in the config/database.php file. You can define all database connection configurations in this file and specify the default database connection. This file provides examples of most database configurations supported by Laravel.

By default, Laravel's example environment configuration uses Laravel Homestead (it is a small virtual machine that allows you to easily develop using Laravel locally). You can modify this configuration file according to the needs of the local database.

SQLite configuration

After creating a new SQLite database using a create command such as touch database/database.sqlite, you You can use the absolute path to the database and configure the environment variable to point to this newly created database:

DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite

To enable foreign key constraints for SQLite connections, the DB_foreign_KEYS environment variable should be set to true:

DB_FOREIGN_KEYS=true

URLs form configuration

Usually, database connections use multiple configuration values, such as host, database, username, password, etc. Each of these configuration values ​​has its corresponding environment variable. This means that there are multiple environment variables that need to be managed when configuring database connection information on the production server.

Some managed database providers (such as Heroku) provide a single database "URL" that contains all connection information for the database in a single string. A sample database URL might look like this:

mysql://root:password@127.0.0.1/forge?charset=UTF-8
这些 URLs 通常遵循标准模式约定:
driver://username:password@host:port/database?options

For convenience, Laravel supports these URLs as an alternative to configuring the database using multiple configuration options. If the url (or corresponding DATABASE_URL environment variable) configuration option is present, that option will be used to extract database connection and credential information.

Read-write separation

Sometimes you want the SELECT statement to use one database connection, and the INSERT, UPDATE, and DELETE statements to use another database connection. In Laravel, whether you use native queries, query builders, or Eloquent ORM, you can easily implement it.

In order to understand how read-write separation is configured, let's first look at an example:

'mysql' => [
    'read' => [
        'host' => [
            '192.168.1.1',
            '196.168.1.2',
        ],
    ],
    'write' => [
        'host' => [
            '196.168.1.3',
        ],
    ],
    'sticky' => true,
    'driver' => 'mysql',
    'database' => 'database',
    'username' => 'root',
    'password' => '',
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
],

Note that in the above example, three keys have been added to the configuration array, namely read , write and sticky. Both read and write contain an array with the key host. The other database options for read and write are in the array with the key mysql.

If you want to rewrite the configuration in the main array, just modify the read and write arrays. So, in this example: 192.168.1.1 and 192.168.1.2 will connect to the host as "read", while 192.168.1.3 will connect to the host as "write". These two connections will share various configurations of the mysql array, such as database credentials (username/password), prefix, character encoding, etc.

sticky option

sticky is an optional value that is used to immediately read records that have been written to the database during the current request cycle. If the sticky option is enabled and a "write" operation is performed during the current request cycle, any "read" operations will use the "write" connection. This ensures that data written in the same request cycle can be read immediately, thereby avoiding the problem of data inconsistency caused by master-slave synchronization delay. Whether to enable it, however, depends on the application's needs.

Using multiple database connections

When using multiple database connections, you can access each connection through the connection method of the DB Facade facade. The parameter name passed to the connection method should be a value in the connections array in the config/database.php configuration file:

$users = DB::connection('foo')->select(...);

You can also use the getPdo method on a connection instance to access the underlying PDO instance:

$pdo = DB::connection()->getPdo();

执行原生 SQL 查询

一旦配置好数据库连接后,便可以使用 DB facade 门面运行查询。DB facade 为每种类型的查询提供了相应的方法:select,update,insert,delete 和 statement。

执行 Select 查询

你可以使用 DB Facade 的 select 方法来运行基础的查询语句:

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
    /**
     * 显示应用程序中所有用户的列表
     *
     * @return Response
     */
    public function index()
    {
        $users = DB::select(&#39;select * from users where active = ?&#39;, [1]);
        return view(&#39;user.index&#39;, [&#39;users&#39; => $users]);
    }
}

传递给 select 方法的第一个参数就是一个原生的 SQL 查询,而第二个参数则是需要绑定到查询中的参数值。通常,这些值用于约束 where 语句。参数绑定可以防止 SQL 注入。

select 方法将始终返回一个 array 数组,数组中的每个结果都是一个 stdClass 对象,可以像下面这样访问结果中的数值:

foreach ($users as $user) {
    echo $user->name;
}

使用命名绑定

除了使用 ? 表示参数绑定外,你还可以使用命名绑定的形式来执行一个查询:

$results = DB::select(&#39;select * from users where id = :id&#39;, [&#39;id&#39; => 1]);

执行 Insert 语句

你可以使用 DB Facade 的 insert 方法来执行 insert 语句。与 select 方法一样,该方法将原生 SQL 查询作为其第一个参数,并将绑定的数据作为第二个参数:

DB::insert(&#39;insert into users (id, name) values (?, ?)&#39;, [1, &#39;Dayle&#39;]);

执行 Update 语句

update 方法用于更新数据库中现有的记录。该方法返回该执行语句影响的行数:

$affected = DB::update(&#39;update users set votes = 100 where name = ?&#39;, [&#39;John&#39;]);

执行 Delete 语句

delete 方法用于从数据库中删除记录。与 update 方法一样,返回受该执行语句影响的行数:

$deleted = DB::delete(&#39;delete from users&#39;);

执行普通语句

有些数据库语句不会有任何返回值。对于这些语句,你可以使用 DB Facade 的 statement 方法来运行:

DB::statement(&#39;drop table users&#39;);

运行未预处理的语句

有时你可能希望在不绑定任何值的情况下运行语句。对于这些类型的操作,可以使用 DB Facade 的 unprepared 方法:

DB::unprepared(&#39;update users set votes = 100 where name = "Dries"&#39;);

请注意,这些语句不会像上面的语句那样绑定值。它们可以打开你的应用程序进行 SQL 注入,应该非常小心地使用。

隐式提交

在事务中使用 DB 外观的 statement 和 unprepared 方法时,必须小心避免导致 [隐式提交] 的语句 (https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html)。 这些语句将导致数据库引擎间接提交整个事务,从而使 Laravel 不知道数据库的事务级别。这种语句的一个例子是创建数据库表:

DB::unprepared(&#39;create table a (col varchar(1) null)&#39;);

请参考 MySQL 手册中的触发隐式提交的所有语句列表。

监听查询事件

如果你想监控程序执行的每一个 SQL 查询,你可以使用 listen 方法。这个方法对于记录查询或调试非常有用。你可以在 服务提供器 中注册你的查询监听器:

<?php
namespace App\Providers;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /**
     * 注册所有应用的服务
     *
     * @return void
     */
    public function register()
    {
        //
    }
    /**
     * 引导所有应用的服务
     *
     * @return void
     */
    public function boot()
    {
        DB::listen(function ($query) {
            // $query->sql
            // $query->bindings
            // $query->time
        });
    }
}

数据库事务

你可以使用 DB facade 的 transaction 方法在数据库事务中运行一组操作。如果事务的闭包 Closure 中出现一个异常,事务将会回滚。如果事务闭包 Closure 执行成功,事务将自动提交。一旦你使用了 transaction, 就不必担心手动回滚或提交的问题:

DB::transaction(function () {
    DB::table(&#39;users&#39;)->update([&#39;votes&#39; => 1]);
    DB::table(&#39;posts&#39;)->delete();
});

处理死锁

transaction 方法接受一个可选的第二个参数,该参数用来表示事务发生死锁时重复执行的次数。一旦定义的次数尝试完毕,就会抛出一个异常:

DB::transaction(function () {
    DB::table(&#39;users&#39;)->update([&#39;votes&#39; => 1]);
    DB::table(&#39;posts&#39;)->delete();
}, 5);

手动使用事务

如果你想要手动开始一个事务,并且对回滚和提交能够完全控制,那么你可以使用 DB Facade 的 beginTransaction 方法:

DB::beginTransaction();

你可以使用 rollBack 方法回滚事务:

DB::rollBack();

最后,你可以使用 commit 方法提交事务:

DB::commit();

技巧:DB facade 的事务方法同样适用于 查询构造器 和 Eloquent ORM。

连接到数据库 CLI

如果要连接到数据库的 CLI,可以使用 db Artisan 命令:

php artisan db

如果需要,可以指定数据库连接名称以连接到不是默认连接的数据库连接:

php artisan db mysql

【相关推荐:laravel视频教程

The above is the detailed content of What database does laravel support?. For more information, please follow other related articles on the PHP Chinese website!

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
Laravel's Primary Function: Backend DevelopmentLaravel's Primary Function: Backend DevelopmentApr 15, 2025 am 12:14 AM

Laravel's core functions in back-end development include routing system, EloquentORM, migration function, cache system and queue system. 1. The routing system simplifies URL mapping and improves code organization and maintenance. 2.EloquentORM provides object-oriented data operations to improve development efficiency. 3. The migration function manages the database structure through version control to ensure consistency. 4. The cache system reduces database queries and improves response speed. 5. The queue system effectively processes large-scale data, avoid blocking user requests, and improve overall performance.

Laravel's Backend Capabilities: Databases, Logic, and MoreLaravel's Backend Capabilities: Databases, Logic, and MoreApr 14, 2025 am 12:04 AM

Laravel performs strongly in back-end development, simplifying database operations through EloquentORM, controllers and service classes handle business logic, and providing queues, events and other functions. 1) EloquentORM maps database tables through the model to simplify query. 2) Business logic is processed in controllers and service classes to improve modularity and maintainability. 3) Other functions such as queue systems help to handle complex needs.

Laravel's Versatility: From Simple Sites to Complex SystemsLaravel's Versatility: From Simple Sites to Complex SystemsApr 13, 2025 am 12:13 AM

The Laravel development project was chosen because of its flexibility and power to suit the needs of different sizes and complexities. Laravel provides routing system, EloquentORM, Artisan command line and other functions, supporting the development of from simple blogs to complex enterprise-level systems.

Laravel (PHP) vs. Python: Development Environments and EcosystemsLaravel (PHP) vs. Python: Development Environments and EcosystemsApr 12, 2025 am 12:10 AM

The comparison between Laravel and Python in the development environment and ecosystem is as follows: 1. The development environment of Laravel is simple, only PHP and Composer are required. It provides a rich range of extension packages such as LaravelForge, but the extension package maintenance may not be timely. 2. The development environment of Python is also simple, only Python and pip are required. The ecosystem is huge and covers multiple fields, but version and dependency management may be complex.

Laravel and the Backend: Powering Web Application LogicLaravel and the Backend: Powering Web Application LogicApr 11, 2025 am 11:29 AM

How does Laravel play a role in backend logic? It simplifies and enhances backend development through routing systems, EloquentORM, authentication and authorization, event and listeners, and performance optimization. 1. The routing system allows the definition of URL structure and request processing logic. 2.EloquentORM simplifies database interaction. 3. The authentication and authorization system is convenient for user management. 4. The event and listener implement loosely coupled code structure. 5. Performance optimization improves application efficiency through caching and queueing.

Why is Laravel so popular?Why is Laravel so popular?Apr 02, 2025 pm 02:16 PM

Laravel's popularity includes its simplified development process, providing a pleasant development environment, and rich features. 1) It absorbs the design philosophy of RubyonRails, combining the flexibility of PHP. 2) Provide tools such as EloquentORM, Blade template engine, etc. to improve development efficiency. 3) Its MVC architecture and dependency injection mechanism make the code more modular and testable. 4) Provides powerful debugging tools and performance optimization methods such as caching systems and best practices.

Which is better, Django or Laravel?Which is better, Django or Laravel?Mar 28, 2025 am 10:41 AM

Both Django and Laravel are full-stack frameworks. Django is suitable for Python developers and complex business logic, while Laravel is suitable for PHP developers and elegant syntax. 1.Django is based on Python and follows the "battery-complete" philosophy, suitable for rapid development and high concurrency. 2.Laravel is based on PHP, emphasizing the developer experience, and is suitable for small to medium-sized projects.

Which is better PHP or Laravel?Which is better PHP or Laravel?Mar 27, 2025 pm 05:31 PM

PHP and Laravel are not directly comparable, because Laravel is a PHP-based framework. 1.PHP is suitable for small projects or rapid prototyping because it is simple and direct. 2. Laravel is suitable for large projects or efficient development because it provides rich functions and tools, but has a steep learning curve and may not be as good as pure PHP.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

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.