I see similar questions at SO, but they are outdated and no longer actual. 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
. 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.
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.