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

王林
Release: 2023-07-31 16:46:01
Original
1044 people have browsed it

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,
    ],
    // 其他类型的数据库连接配置
],
Copy after login
  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';
    // 其他模型的属性和方法
}
Copy after login
  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;
    }
    Copy after login
  • Conditional query:

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

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

    $users = User::where('age', '>', 18)->get();
    foreach ($users as $user) {
      echo $user->name;
    }
    Copy after login
  • 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;
    }
    Copy after login
  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();
    Copy after login
  • Update an existing record:

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

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

    User::where('id', 1)->update(['name' => 'Jane Doe']);
    Copy after login
  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();
    Copy after login
  • Delete multiple records using the destroy method :

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

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

    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!

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