Home > Backend Development > PHP Tutorial > How to use Doctrine ORM for database operations in Symfony framework

How to use Doctrine ORM for database operations in Symfony framework

WBOY
Release: 2023-07-29 16:18:02
Original
1640 people have browsed it

How to use Doctrine ORM in Symfony framework for database operations

Introduction:
Symfony framework is a popular PHP framework that provides many powerful tools and components for quickly and easily Build web applications. One of the key components is Doctrine ORM, which provides an elegant way to handle database operations.

This article will introduce in detail how to use Doctrine ORM to perform database operations in the Symfony framework. We will cover the following topics:

  1. Configuring Doctrine ORM
  2. Entity classes and database mapping
  3. Performing CRUD operations
  4. Query builder and DQL queries

1. Configure Doctrine ORM
To use Doctrine ORM in Symfony, we first need to install Doctrine Bundle. Run the following command in the terminal:

composer require doctrine/doctrine-bundle
Copy after login

After the installation is complete, we need to configure Doctrine’s connection information. Add the following to the .env file:

DATABASE_URL=mysql://username:password@127.0.0.1:3306/db_name
Copy after login

Replace username, password, and db_name with your own database connection information.

Then, open the config/packages/doctrine.yaml file and add the following configuration:

doctrine:
    dbal:
        url: '%env(resolve:DATABASE_URL)%'
        driver: 'pdo_mysql'
        charset: utf8mb4
    orm:
        auto_generate_proxy_classes: true
        naming_strategy: doctrine.orm.naming_strategy.underscore
        auto_mapping: true
Copy after login

2. Entity classes and database mapping
Doctrine ORM uses entity classes to represent tables in the database. We need to create an entity class for each table and map it with the database.

First, create a directory named src/Entity. Create a file called User.php in that directory and add the following content:

namespace AppEntity;

use DoctrineORMMapping as ORM;

/**
 * @ORMEntity
 * @ORMTable(name="users")
 */
class User
{
    /**
     * @ORMId
     * @ORMGeneratedValue(strategy="AUTO")
     * @ORMColumn(type="integer")
     */
    private $id;

    /**
     * @ORMColumn(type="string")
     */
    private $name;

    // 添加其他属性和方法...

    // Getter和Setter方法...

    // 其他业务逻辑...
}
Copy after login

In the above example, we created a file called User's entity class and maps it to the users table. The id attribute is defined as an automatically generated primary key, and the name attribute is a string.

3. Perform CRUD operations
Doctrine ORM provides many simple methods to perform CRUD (create, read, update, and delete) operations.

Create new entity:

public function create()
{
    $entityManager = $this->getDoctrine()->getManager();

    $user = new User();
    $user->setName('John Doe');

    $entityManager->persist($user);
    $entityManager->flush();

    return new Response('User created!');
}
Copy after login

Read entity:

public function read($id)
{
    $entityManager = $this->getDoctrine()->getManager();

    $user = $entityManager->getRepository(User::class)->find($id);

    if (!$user) {
        throw $this->createNotFoundException('User not found!');
    }

    return new Response('User name: ' . $user->getName());
}
Copy after login

Update entity:

public function update($id)
{
    $entityManager = $this->getDoctrine()->getManager();

    $user = $entityManager->getRepository(User::class)->find($id);

    if (!$user) {
        throw $this->createNotFoundException('User not found!');
    }

    $user->setName('Jane Doe');

    $entityManager->flush();

    return new Response('User updated!');
}
Copy after login

Delete entity:

public function delete($id)
{
    $entityManager = $this->getDoctrine()->getManager();

    $user = $entityManager->getRepository(User::class)->find($id);

    if (!$user) {
        throw $this->createNotFoundException('User not found!');
    }

    $entityManager->remove($user);
    $entityManager->flush();

    return new Response('User deleted!');
}
Copy after login

IV. Query builder and DQL query
In addition to basic CRUD operations, we can also use query builder and DQL (Doctrine Query Language) to perform complex queries.

Query builder example:

public function findByName($name)
{
    $entityManager = $this->getDoctrine()->getManager();

    $queryBuilder = $entityManager->createQueryBuilder();
    $queryBuilder->select('u')
        ->from(User::class, 'u')
        ->where('u.name = :name')
        ->setParameter('name', $name);

    $users = $queryBuilder->getQuery()->getResult();

    return new Response('Users found: ' . count($users));
}
Copy after login

DQL query example:

public function findByAge($age)
{
    $entityManager = $this->getDoctrine()->getManager();

    $query = $entityManager->createQuery(
        'SELECT u FROM AppEntityUser u WHERE u.age > :age'
    )->setParameter('age', $age);

    $users = $query->getResult();

    return new Response('Users found: ' . count($users));
}
Copy after login

Conclusion:
Using Doctrine ORM in Symfony framework for database operations is very simple and efficient . This article explains how to configure Doctrine ORM, create entity classes, perform CRUD operations, and use query builders and DQL queries. I hope this article can help you better use Symfony and Doctrine ORM to develop high-quality web applications.

The above is the detailed content of How to use Doctrine ORM for database operations in Symfony 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