[英]How to create a table from entity in Doctrine 2
我在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;
}
}
在單元測試中,我有一個工作代碼,如下所示:
<?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);
}
}
這段代碼行得通,只是因為在我的數據庫中已經有一個表test_model
。 但是我想在我的測試服中動態創建它,並在所有測試后銷毀它。 如何以編程方式進行?
Doctrine文檔詳細描述了模式生成 。
這是一個簡單的示例:
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.