Home >Backend Development >PHP Tutorial >How to use Eloquent ORM for database operations in Laravel framework

How to use Eloquent ORM for database operations in Laravel framework

王林
王林Original
2023-07-31 16:43:531050browse

How to use Eloquent ORM for database operations in the Laravel framework

Introduction:
Laravel is a popular PHP framework that provides rich features and tools to simplify the development process. One of the powerful features is Eloquent ORM, which provides us with an elegant and concise way to perform database operations. This article will introduce how to use Eloquent ORM to perform database operations in the Laravel framework and give some practical code examples.

  1. Configuring the database connection
    First, before using Eloquent ORM, we need to configure the database connection in Laravel. Open the configuration file config/database.php, find the connections array, and configure it according to your own database type and credentials. For example:
'connections' => [
    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix'    => '',
        'strict'    => true,
        'engine'    => null,
    ],
    // 其他类型的数据库连接配置
],
  1. Define model
    In Eloquent ORM, a model represents a table in the database. We can define a model to interact with each table. To define a model, you need to inherit from the IlluminateDatabaseEloquentModel class and specify the table name associated with it. For example, we have a user table users, and we can create a User model:
namespace AppModels;

use IlluminateDatabaseEloquentModel;

class User extends Model
{
    protected $table = 'users';
    // 其他模型的属性和方法
}
  1. Query data
    Using Eloquent ORM, we Data can be queried using various methods. The following are some commonly used methods and examples:
  • Query all data:

    $users = User::all();
    foreach ($users as $user) {
      echo $user->name;
    }
  • Conditional query:

    $user = User::where('id', 1)->first();
    echo $user->name;
  • Sort and limit query results:

    $users = User::orderBy('created_at', 'desc')->take(10)->get();
    foreach ($users as $user) {
      echo $user->name;
    }
  • Use where conditional query:

    $users = User::where('age', '>', 18)->get();
    foreach ($users as $user) {
      echo $user->name;
    }
  • Use native SQL query:

    $users = User::select(DB::raw('count(*) as user_count'))->groupBy('account_id')->get();
    foreach ($users as $user) {
      echo $user->user_count;
    }
  1. Create and update data
    Using Eloquent ORM, we can easily create and update records in the database. Here are some examples:
  • Create a new record:

    $user = new User;
    $user->name = 'John Doe';
    $user->email = 'johndoe@example.com';
    $user->save();
  • Update an existing record:

    $user = User::find(1);
    $user->name = 'Jane Doe';
    $user->save();
  • Use the create method to create a record:

    $user = User::create([
      'name' => 'John Doe',
      'email' => 'johndoe@example.com',
    ]);
  • Use the update method to update a record:

    User::where('id', 1)->update(['name' => 'Jane Doe']);
  1. Delete Data
    Using Eloquent ORM, we can easily delete records in the database. Here are some examples:
  • Delete a single record:

    $user = User::find(1);
    $user->delete();
  • Delete multiple records using the destroy method :

    User::destroy([1, 2, 3]);
  • Use delete method to delete records based on conditions:

    User::where('age', '<', 18)->delete();

Conclusion:
Using Eloquent ORM, We can easily perform database operations without writing too many SQL statements. With a few simple lines of code, we can query, create, update and delete records in the database. I hope this article will help you use Eloquent ORM for database operations in the Laravel framework!

Reference materials:

  • Laravel official documentation: https://laravel.com/docs/8.x/eloquent

The above is the detailed content of How to use Eloquent ORM for database operations in Laravel framework. 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