[英]How to create a table from entity in Doctrine 2
I see similar questions at SO, but they are outdated and no longer actual. 我在SO上看到了类似的问题,但是它们已经过时了,不再是实际的了。 So, what I want is to create tables in database using models definition.
因此,我要使用模型定义在数据库中创建表。 So, I have a model which looks like so:
因此,我有一个看起来像这样的模型:
<?php
namespace Tests\Integration\Models;
/**
* @Entity
* @Table(name="test_model")
*/
class TestModel
{
/**
* @Id @Column(type="integer")
* @GeneratedValue
*/
protected $id;
/** @Column(type="integer") */
protected $a;
public function getId()
{
return $this->id;
}
public function getA()
{
return $this->a;
}
public function setA($a)
{
$this->a = $a;
}
}
In my unit-test I have a working code, looking like: 在单元测试中,我有一个工作代码,如下所示:
<?php
namespace Tests\Integration;
use PHPUnit\Framework\TestCase;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;
use Tests\Integration\Models\TestModel;
use Tests\Integration\Models\TestModelRepository;
final class IntegrationOrmTest extends TestCase
{
protected static $em;
protected static $er;
public static function setUpBeforeClass()
{
$params = [
'driver' => getenv("TEST_DB_DRIVER"),
'host' => getenv("TEST_DB_HOST"),
'dbname' => getenv("TEST_DB_NAME"),
'user' => getenv("TEST_DB_USER"),
'password' => getenv("TEST_DB_PASSWORD"),
'port' => getenv("TEST_DB_PORT"),
];
$config = Setup::createAnnotationMetadataConfiguration(["./Models"], true);
self::$em = EntityManager::create($params, $config);
self::$er = new TestModelRepository(self::$em);
}
public function testEquals()
{
//works perfectly fine
$data = new TestModel();
$data->setA(123);
self::$er->save($data);
self::$em->flush();
$this->assertTrue(true);
}
}
This code works, just because in my database there is already a table test_model
. 这段代码行得通,只是因为在我的数据库中已经有一个表
test_model
。 But I want to create it dynamically in my test suit and destroy it after all tests. 但是我想在我的测试服中动态创建它,并在所有测试后销毁它。 How can I do it programmatically?
如何以编程方式进行?
The Doctrine docs describe schema generation in some detail. Doctrine文档详细描述了模式生成 。
Here is a simple example: 这是一个简单的示例:
final class IntegrationOrmTest extends TestCase
{
public static function setUpBeforeClass()
{
$params = [
'driver' => "pdo_mysql",
'host' => "localhost",
'dbname' => "s43x",
'user' => "impd",
'password' => "JalenHurts",
//'port' => getenv("TEST_DB_PORT"),
];
$config = Setup::createAnnotationMetadataConfiguration(["./Models"], true);
self::$em = $em = EntityManager::create($params, $config);
$tool = new \Doctrine\ORM\Tools\SchemaTool($em);
$classes = array(
$em->getClassMetadata(TestModel::class),
);
$tool->dropSchema($classes); // Empty out any current schema
$tool->createSchema($classes);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.