![](/img/trans.png)
[英]How can I filter Entity relationships to return the main object, but not the related one? (Symfony2/Doctrine2)
[英]Doctrine: How to create entity-related tables on demand? (if i want to keep one SQL schema source)
有沒有辦法告訴 Doctrine 許多實體的名稱並創建它們的相關表(包括外鍵等)?
我的場景:
我想在我的 Doctrine 實體上有注釋作為我的數據庫模式的唯一來源。 這意味着,例如對於測試,我不想在 SQL 文件或其他文件中維護這些信息的副本。
明確地說,我指的是實體類中的注釋,如下所示:
<?php
namespace App\Entity;
/**
* @ORM\Entity(repositoryClass="App\Repository\UserRepository")
* @UniqueEntity(fields={"email"}, message="There is already an account with this email")
*
* @ORM\Table(
* uniqueConstraints={
* @ORM\UniqueConstraint(name="email", columns={"email"})
* }
* )
*/
class User
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="string", length=180, nullable=false)
*/
private $email;
// ...
}
我想做什么:
在我的測試中,我想為User
創建表,例如:
<?php
namespace App\Test;
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class SomeTestCase extends KernelTestCase
{
public function setUp()
{
// ...
$this->entityManager = $kernel->getContainer()
->get('doctrine')
->getManager();
}
public function test1()
{
// Is there a function available which has this functionality?
$this->entityManager->createTableForEntity('App\Entity\User'); // <---------
// ...
}
}
那可能嗎? 如果沒有,即使一次創建所有表對我來說也很好。
還有另一種方法可以實現嗎?
我使用以下命令在我的測試中創建所有表:
use Doctrine\ORM\Tools\SchemaTool;
$metadatas = $this->entityManager->getMetadataFactory()->getAllMetadata();
$schemaTool = new SchemaTool($this->entityManager);
$schemaTool->updateSchema($metadatas);
MetadataFactory 類上有一個方法getMetadataFactory()
所以我想如果你只想創建一個表,下面的方法也應該有效。
$metadata = $this->entityManager->getMetadataFactory()->getMetadataFor('App\Entity\User');
$schemaTool = new SchemaTool($this->entityManager);
$schemaTool->updateSchema($metadata);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.