Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Laravel manages MySQL variables?

Tags:

php

mysql

laravel

If I do

DB::statement("SET @foo := 1;");
DB::select("SELECT @foo;");

I get the expected 1 in the result. But I can't find anywhere whether it is a guaranteed result. If I understand correctly the variables are specific to MySQL connection. So is it possible that those 2 statements will be performed on different connections for some reason and I'll get different result? Can I rely on it to always work?

like image 324
Poma Avatar asked Dec 17 '18 14:12

Poma


People also ask

Does Laravel support MySQL?

Currently Laravel supports four database systems: MySQL, Postgres, SQLite, and SQL Server.

Does Laravel use PDO?

The PHP Data Objects (PDO) The PDO is a standard interface for accessing databases in PHP, Laravel uses the PDO to run all kinds of queries. However, you can configure a connection to use a separate read & write PDO objects for read/write operations.

What is the support of MySQL in Laravel?

Laravel by default provides the support of MySQL. MySQL is a well known, open-source RDBMS (Relational Database Management System). Step 1: First we have to create a database.

How do I configure Laravel's database services?

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.

What is database_url in Laravel?

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.

What do database URLs look like in Laravel?

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.


1 Answers

To ensure both statements are always executed as one single statement you can use database transactions:

DB::transaction(function () {
    DB::statement("SET @foo := 1;");
    DB::select("SELECT @foo;");
});

This guarantees that each transaction is treated as a single "unit" (atomicity). There are two possibilities: both statements are executed as one or if a failure occurs non statement is executed at all.

The next guarantee is: both statements are executed in isolation that means if you execute this code concurrently it is always guaranteed that the transactions were executed sequentially.

like image 197
maxwilms Avatar answered Oct 22 '22 15:10

maxwilms