Laravel — Database
Laravel делает взаимодействие с базами данных чрезвычайно простым в различных базах данных базы данных, используя либо сырой SQL, беглый конструктор запросов и Eloquent ORM . В настоящее время Laravel поддерживает четыре базы данных:
- MySQL
- PostgreSQL
- SQLite
- SQL Server
Конфигурация
Конфигурация базы данных для вашего приложения находится по адресу . В этом файле вы можете определить все ваши соединения с базой данных, а также указать, какое соединение должно использоваться по умолчанию. Примеры для большинства поддерживаемых систем баз данных приведены в этом файле. config/database.php
По умолчанию образец конфигурации среды Laravel готов к использованию с Laravel Homestead , которая является удобной виртуальной машиной для разработки Laravel на вашей локальной машине. Вы можете изменять эту конфигурацию по мере необходимости для вашей локальной базы данных.
Конфигурация SQLite
После создания новой базы данных SQLite с помощью такой команды, как , вы можете легко настроить переменные среды, чтобы они указывали на эту вновь созданную базу данных, используя абсолютный путь к базе данных: touch database/database.sqlite
Чтобы включить ограничения внешнего ключа для соединений SQLite, необходимо добавить foreign_key_constraints параметр в файл конфигурации: config/database.php
Конфигурация с использованием URL
Как правило, соединение с базой данных настраиваются с помощью нескольких значений конфигурации , таких как host , database , username , password и т.д. Каждый из этих значений конфигурации имеет свою собственную переменную , соответствующую среду. Это означает, что при настройке информации о соединении с вашей базой данных на рабочем сервере вам необходимо управлять несколькими переменными среды.
Некоторые поставщики управляемых баз данных, такие как Heroku, предоставляют единый «URL» базы данных, который содержит всю информацию о соединении для базы данных в одной строке. Пример URL базы данных может выглядеть примерно так:
Эти URL обычно следуют стандартному соглашению схемы:
Для удобства Laravel поддерживает эти URL-адреса в качестве альтернативы настройке базы данных с несколькими вариантами конфигурации. Если присутствует параметр конфигурации url (или соответствующая DATABASE_URL переменная среды), он будет использоваться для извлечения соединения с базой данных и информации о полномочиях.
Чтение и запись подключений
Иногда вы можете использовать одно соединение с базой данных для операторов SELECT, а другое — для операторов INSERT, UPDATE и DELETE. Laravel делает это быстрым, и правильные соединения всегда будут использоваться независимо от того, используете ли вы необработанные запросы, построитель запросов или Eloquent ORM.
Чтобы увидеть, как должны быть настроены соединения для чтения / записи, давайте посмотрим на этот пример:
Обратите внимание , что три ключа , которые были добавлены в массив конфигурации: read , write и sticky . read И write ключи имеют значение массива , содержащее один ключ: host . Остальные параметры базы данных для read и write соединений будут объединены с основной mysql массив.
Вам нужно всего лишь поместить элементы в read и write массивы , если вы хотите , чтобы переопределить значения из основного массива. Таким образом, в этом случае будет использоваться в качестве хоста для соединения «чтение», в то время как будет использоваться для соединения «запись». Учетные данные базы данных, префикс, набор символов и все другие параметры в основном массиве будут общими для обоих подключений. 192.168.1.1 192.168.1.3 mysql
sticky Вариант
Этот sticky параметр является необязательным значением, которое можно использовать для немедленного чтения записей, которые были записаны в базу данных во время текущего цикла запроса. Если sticky опция включена и операция «запись» была выполнена с базой данных во время текущего цикла запроса, любые дальнейшие операции «чтения» будут использовать соединение «запись». Это гарантирует, что любые данные, записанные во время цикла запроса, могут быть немедленно прочитаны обратно из базы данных во время того же запроса. Вам решать, является ли это желаемым поведением для вашего приложения.
Использование нескольких подключений к базе данных
При использовании нескольких соединений вы можете получить доступ к каждому соединению с помощью connection метода на DB фасаде. name Передается connection методу должен соответствовать одному из соединений , перечисленных в вашем файле конфигурации: config/database.php
Вы также можете получить доступ к необработанному базовому экземпляру PDO, используя getPdo метод для экземпляра соединения:
Выполнение необработанных SQL-запросов
После того, как вы настроили соединение с базой данных, вы можете запускать запросы, используя DB фасад. DB Фасад предоставляет методы для каждого типа запроса: select , update , insert , delete и statement .
Выполнение выбранного запроса
Чтобы выполнить базовый запрос, вы можете использовать select метод на DB фасаде:
Первым аргументом, передаваемым select методу, является необработанный запрос SQL, а вторым аргументом являются любые привязки параметров, которые должны быть связаны с запросом. Как правило, это значения where ограничений предложения. Привязка параметров обеспечивает защиту от внедрения SQL.
select Метод всегда будет возвращать array результаты. Каждый результат в массиве будет stdClass объектом PHP , позволяющим вам получить доступ к значениям результатов:
Использование именованных привязок
Вместо использования ? для представления привязок параметров, вы можете выполнить запрос, используя именованные привязки:
Запуск оператора вставки
Чтобы выполнить insert оператор, вы можете использовать insert метод на DB фасаде. Например select , этот метод принимает необработанный SQL-запрос в качестве первого аргумента и привязки в качестве второго аргумента:
Запуск оператора обновления
Этот update метод следует использовать для обновления существующих записей в базе данных. Количество строк, затронутых оператором, будет возвращено:
Запуск оператора удаления
delete Метод должен быть использован для удаления записей из базы данных. Мол update , будет возвращено количество затронутых строк:
Запуск общего заявления
Некоторые операторы базы данных не возвращают никакого значения. Для этих типов операций вы можете использовать statement метод на DB фасаде:
Прослушивание событий запроса
Если вы хотите получать каждый SQL-запрос, выполняемый вашим приложением, вы можете использовать этот listen метод. Этот метод полезен для регистрации запросов или отладки. Вы можете зарегистрировать прослушиватель запросов у поставщика услуг :
Операции с базой данных
Вы можете использовать transaction метод на DB фасаде для запуска набора операций внутри транзакции базы данных. Если Closure в транзакции возникнет исключение , транзакция будет автоматически откатана. Если Closure выполняется успешно, транзакция будет автоматически зафиксирована. Вам не нужно беспокоиться о ручном откате или фиксации при использовании transaction метода:
Обработка тупиков
transaction Метод принимает необязательный второй аргумент , который определяет, сколько раз транзакция должна быть повторная попытка при возникновении взаимоблокировки. Как только эти попытки будут исчерпаны, будет сгенерировано исключение:
Использование транзакций вручную
Если вы хотите начать транзакцию вручную и иметь полный контроль над откатами и фиксациями, вы можете использовать beginTransaction метод на DB фасаде:
Вы можете откатить транзакцию с помощью rollBack метода:
Наконец, вы можете совершить транзакцию с помощью commit метода:
В DB методах транзакционных фасадных контролируют сделки и для конструктора запросов и красноречивого ОРМА .
Database: Getting Started
Almost every modern web application interacts with a database. Laravel makes interacting with databases extremely simple across a variety of supported databases using raw SQL, a fluent query builder, and the Eloquent ORM. Currently, Laravel provides first-party support for five databases:
- MariaDB 10.2+ (Version Policy)
- MySQL 5.7+ (Version Policy)
- PostgreSQL 10.0+ (Version Policy)
- SQLite 3.8.8+
- SQL Server 2017+ (Version Policy)
Configuration
The configuration for Laravel’s database services is located in your application’s config/database.php configuration file. In this file, you may define all of your database connections, as well as specify which connection should be used by default. Most of the configuration options within this file are driven by the values of your application’s environment variables. Examples for most of Laravel’s supported database systems are provided in this file.
By default, Laravel’s sample environment configuration is ready to use with Laravel Sail, which is a Docker configuration for developing Laravel applications on your local machine. However, you are free to modify your database configuration as needed for your local database.
SQLite Configuration
SQLite databases are contained within a single file on your filesystem. You can create a new SQLite database using the touch command in your terminal: touch database/database.sqlite . After the database has been created, you may easily configure your environment variables to point to this database by placing the absolute path to the database in the DB_DATABASE environment variable:
To enable foreign key constraints for SQLite connections, you should set the DB_FOREIGN_KEYS environment variable to true :
Microsoft SQL Server Configuration
To use a Microsoft SQL Server database, you should ensure that you have the sqlsrv and pdo_sqlsrv PHP extensions installed as well as any dependencies they may require such as the Microsoft SQL ODBC driver.
Configuration Using URLs
Typically, database connections are configured using multiple configuration values such as host , database , username , password , etc. Each of these configuration values has its own corresponding environment variable. This means that when configuring your database connection information on a production server, you need to manage several environment variables.
Some managed database providers such as AWS and Heroku provide a single database "URL" that contains all of the connection information for the database in a single string. An example database URL may look something like the following:
These URLs typically follow a standard schema convention:
For convenience, Laravel supports these URLs as an alternative to configuring your database with multiple configuration options. If the url (or corresponding DATABASE_URL environment variable) configuration option is present, it will be used to extract the database connection and credential information.
Read & Write Connections
Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM.
To see how read / write connections should be configured, let’s look at this example:
Note that three keys have been added to the configuration array: read , write and sticky . The read and write keys have array values containing a single key: host . The rest of the database options for the read and write connections will be merged from the main mysql configuration array.
You only need to place items in the read and write arrays if you wish to override the values from the main mysql array. So, in this case, 192.168.1.1 will be used as the host for the "read" connection, while 192.168.1.3 will be used for the "write" connection. The database credentials, prefix, character set, and all other options in the main mysql array will be shared across both connections. When multiple values exist in the host configuration array, a database host will be randomly chosen for each request.
The sticky Option
The sticky option is an optional value that can be used to allow the immediate reading of records that have been written to the database during the current request cycle. If the sticky option is enabled and a "write" operation has been performed against the database during the current request cycle, any further "read" operations will use the "write" connection. This ensures that any data written during the request cycle can be immediately read back from the database during that same request. It is up to you to decide if this is the desired behavior for your application.
Running SQL Queries
Once you have configured your database connection, you may run queries using the DB facade. The DB facade provides methods for each type of query: select , update , insert , delete , and statement .
Running A Select Query
To run a basic SELECT query, you may use the select method on the DB facade:
The first argument passed to the select method is the SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the where clause constraints. Parameter binding provides protection against SQL injection.
The select method will always return an array of results. Each result within the array will be a PHP stdClass object representing a record from the database:
Selecting Scalar Values
Sometimes your database query may result in a single, scalar value. Instead of being required to retrieve the query’s scalar result from a record object, Laravel allows you to retrieve this value directly using the scalar method:
Using Named Bindings
Instead of using ? to represent your parameter bindings, you may execute a query using named bindings:
Running An Insert Statement
To execute an insert statement, you may use the insert method on the DB facade. Like select , this method accepts the SQL query as its first argument and bindings as its second argument:
Running An Update Statement
The update method should be used to update existing records in the database. The number of rows affected by the statement is returned by the method:
Running A Delete Statement
The delete method should be used to delete records from the database. Like update , the number of rows affected will be returned by the method:
Running A General Statement
Some database statements do not return any value. For these types of operations, you may use the statement method on the DB facade:
Running An Unprepared Statement
Sometimes you may want to execute an SQL statement without binding any values. You may use the DB facade’s unprepared method to accomplish this:
Since unprepared statements do not bind parameters, they may be vulnerable to SQL injection. You should never allow user controlled values within an unprepared statement.
Implicit Commits
When using the DB facade’s statement and unprepared methods within transactions you must be careful to avoid statements that cause implicit commits. These statements will cause the database engine to indirectly commit the entire transaction, leaving Laravel unaware of the database’s transaction level. An example of such a statement is creating a database table:
Please refer to the MySQL manual for a list of all statements that trigger implicit commits.
Using Multiple Database Connections
If your application defines multiple connections in your config/database.php configuration file, you may access each connection via the connection method provided by the DB facade. The connection name passed to the connection method should correspond to one of the connections listed in your config/database.php configuration file or configured at runtime using the config helper:
You may access the raw, underlying PDO instance of a connection using the getPdo method on a connection instance:
Listening For Query Events
If you would like to specify a closure that is invoked for each SQL query executed by your application, you may use the DB facade’s listen method. This method can be useful for logging queries or debugging. You may register your query listener closure in the boot method of a service provider:
Database Transactions
You may use the transaction method provided by the DB facade to run a set of operations within a database transaction. If an exception is thrown within the transaction closure, the transaction will automatically be rolled back and the exception is re-thrown. If the closure executes successfully, the transaction will automatically be committed. You don’t need to worry about manually rolling back or committing while using the transaction method:
Handling Deadlocks
The transaction method accepts an optional second argument which defines the number of times a transaction should be retried when a deadlock occurs. Once these attempts have been exhausted, an exception will be thrown:
Manually Using Transactions
If you would like to begin a transaction manually and have complete control over rollbacks and commits, you may use the beginTransaction method provided by the DB facade:
You can rollback the transaction via the rollBack method:
Lastly, you can commit a transaction via the commit method:
The DB facade’s transaction methods control the transactions for both the query builder and Eloquent ORM.
Connecting To The Database CLI
If you would like to connect to your database’s CLI, you may use the db Artisan command:
If needed, you may specify a database connection name to connect to a database connection that is not the default connection:
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel attempts to take the pain out of development by easing common tasks used in most web projects.
- Our Team
- Release Notes
- Getting Started
- Routing
- Blade Templates
- Authentication
- Authorization
- Artisan Console
- Database
- Eloquent ORM
- Testing
- Laracasts
- Laravel News
- Laracon
- Laracon EU
- Jobs
- Forums
- Vehikl
- Tighten
- 64 Robots
- Kirschbaum
- Curotec
- Jump24
- A2 Design
- ABOUT YOU
- Byte 5
- Cubet
- Cyber-Duck
- DevSquad
- Ideil
- Romega Software
- Worksome
- WebReinvent
- Cashier
- Dusk
- Echo
- Envoyer
- Forge
- Homestead
- Horizon
- Mix
- Nova
- Passport
- Scout
- Socialite
- Spark
- Telescope
- Valet
- Vapor
Laravel is a Trademark of Taylor Otwell. Copyright © 2011-2022 Laravel LLC.