symfony利用Doctrine ORM创建数据模型类

配置数据库

配置数据库信息通常在app/config/parameters.yml 文件中:

# app/config/parameters.yml
# This file is auto-generated during the composer install
parameters:
    database_host: 127.0.0.1
    database_port: 3306
    database_name: lt_dai
    database_user: root
    database_password: root
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    secret: **************************

现在Doctrine可以连接你的数据库了,测试创建一个名为lt_dai的数据库,在终端的项目目录下输入

D:\AppServ\www\symfony34\symfony34>php bin/console doctrine:database:create
Could not create database `lt_dai` for connection named default
An exception occurred while executing 'CREATE DATABASE `lt_dai`':

SQLSTATE[HY000]: General error: 1007 Can't create database 'lt_dai'; database exists

因为该数据库名已存在,所以创建失败,代表配置数据库连接参数无误。

创建一个Entity类

同样在终端的项目文件夹中输入:

php bin/console doctrine:generate:entity AppBundle:Product

该命令中AppBundle可以替换成你想要创建的(或者已存在的)bundle名,Product是你创建的Entity模型类名。 

输入后提示如下:

D:\AppServ\www\symfony34\symfony34>php bin/console doctrine:generate:entity AppBundle:Product


  Welcome to the Doctrine2 entity generator



This command helps you generate Doctrine2 entities.

First, you need to give the entity name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post.

The Entity shortcut name [AppBundle:Product]: 

Determine the format to use for the mapping information.

Configuration format (yml, xml, php, or annotation) [annotation]:

Instead of starting with a blank entity, you can add some fields now.
Note that the primary key will be added automatically (named id).

Available types: array, simple_array, json_array, object,
boolean, integer, smallint, bigint, string, text, datetime, datetimetz,
date, time, decimal, float, binary, blob, guid.

New field name (press <return> to stop adding fields):


  Entity generation


  created .\src\AppBundle/Entity/
  created .\src\AppBundle/Entity/Product.php
> Generating entity class D:\AppServ\www\symfony34\symfony34\src\AppBundle\Entity\Product.php: OK!
> Generating repository class D:\AppServ\www\symfony34\symfony34\src\AppBundle\Repository\ProductRepository.php: OK!


  Everything is OK! Now get to work :).

其中提示你输入的信息可以直接回车使用其默认值,此时在你项目的AppBundle中出现了你刚刚创建的Entity:

Product.php中的内容:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Product
 *
 * @ORM\Entity
 * @ORM\Table(name="Product")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\ProductRepository")
 * 
 */
class Product
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;
    

    /**
     * Get id
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }
}

可以看到class上面的默认注释:

@ORM\Table(name="Product")

这个是默认表名跟类名保持一致,要想用Product模型映射到你的目标数据表,你需要把这个注释改成你的数据表名。当然,还有另外一种更加灵活的方法来实现模型类与数据表的映射,下面我们来尝试一下。

自动映射数据模型:

在终端的项目目录下运行:

php bin/console doctrine:mapping:import AppBundle annotation

这个命令会根据你配置中设置的数据库里面的表名及字段自动生成对应的模型类,例如我上面设置的名为lt_dai的数据库中一共有两个数据表,运行此命令后Entity目录中会生成对应的两个模型类:Test,Test2。

数据库结构:

 对应生成的模型类:

其中以test2.php为例,各个字段及属性都自动映射完成,是不是十分方便。

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Test2
 *
 * @ORM\Table(name="test2")
 * @ORM\Entity
 */
class Test2
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="par1", type="string", length=10, nullable=true)
     */
    private $par1;

    /**
     * @var string
     *
     * @ORM\Column(name="par2", type="string", length=10, nullable=true)
     */
    private $par2;


}

 创建数据表/Schema

还记得刚刚创建的Product数据类吗,这个类创建成功了,但是我们的数据库中并没有这个表,使用下面的命令可以自动在数据库中创建这个表:

php bin/console doctrine:schema:update --force

这个命令会根据你创建的模型类自动生成对应的所有数据表,并且已经存在的表不会被重复创建。

验证映射:

php bin/console doctrine:schema:validate

这个命令会验证你创建的模型跟你数据库中的表是否映射成功,如果成功会返回如下信息:

生成Getters和Setters

注意,以上操作目前只是让Doctrine知道了有哪些对象被持久化到数据库,但是类本身还不具备真正的操作数据的功能,要想操作数据我们还需要创建setter和getter方法:

php bin/console doctrine:generate:entities AppBundle/Entity/Product

该命令可以确保 Product 类所有的getter和setter都被生成。这是一个安全的命令行,你可以多次运行它,它只会生成那些不存在的getters和setters(不会替换已有的方法)。将上面命令中的Product分别替换成Test,Test2来为各个数据类添加getter和setter方法,运行后以Test2为例,Test2.php中多了以下代码:

/**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set par1
     *
     * @param string $par1
     *
     * @return Test2
     */
    public function setPar1($par1)
    {
        $this->par1 = $par1;

        return $this;
    }

    /**
     * Get par1
     *
     * @return string
     */
    public function getPar1()
    {
        return $this->par1;
    }

    /**
     * Set par2
     *
     * @param string $par2
     *
     * @return Test2
     */
    public function setPar2($par2)
    {
        $this->par2 = $par2;

        return $this;
    }

    /**
     * Get par2
     *
     * @return string
     */
    public function getPar2()
    {
        return $this->par2;
    }

也可以一次性生成AppBundle下所有的entity的setter和getter方法,而不用一个个地去执行:

php bin/console doctrine:generate:entities AppBundle

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值