Home > PHP Framework > Laravel > Laravel development: How to use Eloquent ORM for database query?

Laravel development: How to use Eloquent ORM for database query?

WBOY
Release: 2023-06-14 12:47:41
Original
1539 people have browsed it

Laravel is a popular PHP development framework that provides a series of tools and helper functions to speed up the development of web applications. Among them, Eloquent ORM is one of the tools used for database operations in the Laravel framework, allowing Laravel developers to query and operate the database more quickly. In this article, we will delve into how to use Eloquent ORM for database queries.

  1. Install Eloquent ORM

First, we need to install Eloquent ORM in the Laravel application. We can install Eloquent ORM through Composer, open the terminal, enter the folder where the Laravel project is located, and enter the following command:

composer require illuminate/database
Copy after login

After the installation is complete, we need to set the database connection in config/database.php, as follows As shown:

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

],
Copy after login

We also need to set the relevant information of the database connection in the .env file, as shown below:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Copy after login
  1. Define the model

Use To perform database query with Eloquent ORM, we need to define the model first. Model refers to the php class that represents the database table. In Laravel, we can generate the model through the artisan command as follows:

php artisan make:model User
Copy after login

This will create a model named User, which will be mapped to the users table in the database by default. If you want to map to another table, specify the table name in the model using the $table attribute.

class User extends Model
{
    protected $table = 'my_users';
}
Copy after login
  1. Query data

Once the model is defined, we can use Eloquent ORM to query the database. The following are some commonly used query operations:

(1) Query all records

$users = User::all();
Copy after login

(2) Query a single record based on ID

$user = User::find(1);
Copy after login

(3) Query based on other conditions Result set

$users = User::where('name', 'John')->get();
Copy after login

We can add a series of constraints in the where method, such as equal to, not equal to, greater than, less than, in, etc.

$users = User::where('name', '=', 'John')->get();
$users = User::where('age', '>', 18)->get();
$users = User::whereIn('id', [1, 2, 3])->get();
Copy after login

(4) Sorting

$users = User::orderBy('name', 'desc')->get();
Copy after login

(5) Query the specified column

$users = User::select('name', 'email')->get();
Copy after login

We can pass multiple parameters in the select method, each parameter represents the column to be queried The name.

(6) Limit the result set

$users = User::skip(10)->take(5)->get();
Copy after login

We can use the skip and take methods to implement paging. The skip method is used to skip a specified number of records, and the take method is used to return a specified number of records. .

(7) Using aggregate functions

$avg_age = User::avg('age');
$max_age = User::max('age');
$min_age = User::min('age');
$count = User::count();
Copy after login

We can use some aggregate functions, such as avg, max, min, count, etc.

  1. Update data

Using Eloquent ORM to update a record, we can first query the record and then call the save method on the model instance.

$user = User::find(1);
$user->name = 'John';
$user->save();
Copy after login

We can also use the update method to update multiple records:

User::where('active', 1)->update(['status' => 'inactive']);
Copy after login
  1. Delete data

Using Eloquent ORM to delete a record, we can first Query the record and then call the delete method on the model instance.

$user = User::find(1);
$user->delete();
Copy after login

We can also use the destroy method to delete multiple records:

User::destroy([1, 2, 3]);
Copy after login

This will delete records with IDs 1, 2 and 3.

  1. Summary

In this article, we introduced in detail how to use Eloquent ORM for database queries. Eloquent ORM is a very powerful and flexible tool in the Laravel framework, which can help us quickly build efficient and maintainable database queries. If you have any questions or comments about Eloquent ORM, please leave them in the comments.

The above is the detailed content of Laravel development: How to use Eloquent ORM for database query?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template