Symfony 2에서 데이터베이스 보기에 대한 엔티티(docrine) 설정 방법
제가 전망표를 가지고 있다고 치자.그리고 나는 그것으로부터 데이터를 하나의 개체로 가져오기를 원합니다.이를 위해 엔티티 클래스를 생성(및 방법)할 수 있습니까(저장 작업 필요 없음)?그냥 보여주고 싶어요.
수락된 답변은 맞지만, 고려해 볼 수 있는 몇 가지 제안을 추가로 드립니다.
엔티티를 읽기 전용으로 표시합니다.
생성자를 비공개로 설정하여 Detrine만 인스턴스를 생성할 수 있습니다.
/**
* @ORM\Entity(readOnly=true)
* @ORM\Table(name="your_view_table")
*/
class YourEntity {
private function __construct() {}
}
보기를 쿼리하는 데 특별한 것은 없으며 가상 테이블일 뿐입니다.기업의 테이블을 이렇게 설정하고 다음을 즐기십시오.
/**
* @ORM\Entity
* @ORM\Table(name="your_view_table")
*/
class YourEntity {
// ...
}
의 두 모두 하고 , 한다면,schema:update
실패할 겁니다
따라서 개체를 읽기 전용으로 표시하고 생성자를 비공개로 만드는 것 외에도 다음과 같은 작업을 수행합니다(Ian Phillips 답변에서 설명).
/**
* @ORM\Entity(readOnly=true)
* @ORM\Table(name="your_view_table")
*/
class YourEntity {
private function __construct() {}
}
스키마를 수행할 때 엔티티를 무시하도록 스키마 도구를 설정해야 합니다. 업데이트...
이를 위해서는 번들에서 이 명령을 생성하고 ignoredEntity 목록에서 youth entity를 설정하기만 하면 됩니다.
src/Acme/CoreBundle/명령/DocrineUpdate 명령.php:
<?php
namespace Acme\CoreBundle\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\Tools\SchemaTool;
class DoctrineUpdateCommand extends \Doctrine\Bundle\DoctrineBundle\Command\Proxy\UpdateSchemaDoctrineCommand {
protected $ignoredEntities = array(
'Acme\CoreBundle\Entity\EntityToIgnore'
);
protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas) {
/** @var $metadata \Doctrine\ORM\Mapping\ClassMetadata */
$newMetadatas = array();
foreach ($metadatas as $metadata) {
if (!in_array($metadata->getName(), $this->ignoredEntities)) {
array_push($newMetadatas, $metadata);
}
}
parent::executeSchemaCommand($input, $output, $schemaTool, $newMetadatas);
}
}
(Alexandru Trandafir Catalin 신용장: 여기서 획득: https://stackoverflow.com/a/25948910/1442457)
그건 그렇고, 이것이 내가 교리에 대한 견해를 가지고 일하는 유일한 방법입니다.해결책이 될 거란 걸...더 나은 방법이 있다면 개방적이거나 제안)
스키마 업데이트를 위해 교리 마이그레이션을 사용하는 경우 위의 답변 외에도 다음 구성이 완벽하게 작동합니다.
/**
* @ORM\Entity(readOnly=true)
* @ORM\Table(name="view_table_name")
*/
class YourEntity {
private function __construct() {}
}
여기까지 위의 답변과 같습니다.여기서 스키마를 바인딩하지 않도록 구성해야 합니다.
doctrine:
dbal:
schema_filter: ~^(?!view_)~
위 필터 정의는 regex를 사용하여 확장할 수 있는 뷰 뿐만 아니라 모든 'view_' 접두사 테이블을 필터링합니다.보기의 이름을 'view_' 접두사로 지었는지 확인하십시오.
그러나 distrine:schema:update --dump-sql은 여전히 뷰를 보여줍니다. 동일한 필터를 스키마 업데이트에도 통합했으면 좋겠습니다.
이 해결책이 다른 사람들에게 도움이 되었으면 좋겠습니다.
출처 : http://symfony.com/doc/current/bundles/DoctrineMigrationsBundle/index.html#manual-tables
및 :)에 합니다. 다음 코드를 에 새 하지 않도록 설정할 수 있습니다. (에: view_your_table) . 그런 다음 다음 다음 코드를 dectrine.yaml에 추가해야 뷰에 새 마이그레이션 파일을 생성할 수 없습니다.schema_filter: ~^(?!view_)~
위의 답변 외에, DriotUpdate 명령을 확장하기 위해 귀하의 예시 코드를 일부 혼합했습니다.
이것은 나의 독트린 업데이트 명령입니다.
class DoctrineUpdateCommand extends UpdateSchemaDoctrineCommand{
protected function executeSchemaCommand(InputInterface $input, OutputInterface $output, SchemaTool $schemaTool, array $metadatas) {
$container = $this->getApplication()->getKernel()->getContainer();
$filterExpr = $container->get('doctrine')->getEntityManager()->getConnection()->getConfiguration()->getFilterSchemaAssetsExpression();
$emptyFilterExpression = empty($filterExpr);
/** @var $newMetadatas \Doctrine\ORM\Mapping\ClassMetadata */
$newMetadatas = array();
foreach ($metadatas as $metadata) {
if(($emptyFilterExpression||preg_match($filterExpr, $metadata->getTableName()))){
array_push($newMetadatas, $metadata);
}
}
parent::executeSchemaCommand($input, $output, $schemaTool, $newMetadatas);
}
}
옳은 길을 주셔서 감사합니다.
Zend 구현에 대한 데이터베이스에 뷰를 도입해야 하는 필요성 때문에 하루를 보냅니다.
앞에서 말한 것처럼, 당신은 엔터티를 만들어야 하고, 이 엔터티는 다음을 가져야 합니다.Id()
주석:
/**
* @Doctrine\ORM\Mapping\Table(name="your_view")
* @Doctrine\ORM\Mapping\Entity(readOnly=true)
*/
class YourViewEntity
{
/**
* @var SomeEntityInterface
* @Doctrine\ORM\Mapping\Id()
* @Doctrine\ORM\Mapping\OneToOne(targetEntity="SomeMainEntity", fetch="LAZY")
* @Doctrine\ORM\Mapping\JoinColumn(nullable=false, referencedColumnName="id")
*/
protected $some;
/**
* @var AnotherEntityInterface
* @Doctrine\ORM\Mapping\ManyToOne(targetEntity="AnotherEntity", fetch="LAZY")
* @Doctrine\ORM\Mapping\JoinColumn(nullable=false, referencedColumnName="id")
*/
protected $another;
// Make the constructor private so that only Doctrine can create instances.
private function __construct() {}
}
또한 Ian Phillips 답변에 설명된 바와 같이 사설 시공자와 함께.하지만 이것은 예방하지 못합니다.orm:schema-tool:update
새로운 개체를 기반으로 표를 만들고, 우리의 관점을 무시하려고...사용하는 사실에도 불구하고orm:schema-tool:update
마이그레이션 스크립트를 사용하기 위해 프로덕션에서 사용하지 않도록 해야 합니다. 개발 목적상 이 작업은 매우 유용합니다.
~하듯이schema_filter: ~^(?!view_)~
둘 다 작동하지 않는 것 같고, 또한 더 이상 사용되지 않는 것 같습니다. 저는 Kamil Adryjanek 페이지에서 추가 옵션을 제시하는 트릭을 찾을 수 있었습니다.EventListener
아니면Subscriber
엔티티 관리자에게, 그것은 우리를 위해 테이블을 만드는 것을 방해할 것입니다.광산 구현은 아래와 같습니다.
class SkipAutogenerateTableSubscriber implements EventSubscriber
{
public const CONFIG_KEY = "skip_autogenerate_entities";
private $ignoredEntities = [];
public function __construct($config)
{
if (array_key_exists(self::CONFIG_KEY, $config)) {
$this->ignoredEntities = (array) $config[self::CONFIG_KEY];
}
}
public function getSubscribedEvents()
{
return [
ToolEvents::postGenerateSchema
];
}
public function postGenerateSchema(GenerateSchemaEventArgs $args)
{
$schema = $args->getSchema();
$em = $args->getEntityManager();
$ignoredTables = [];
foreach ($this->ignoredEntities as $entityName) {
$ignoredTables[] = $em->getClassMetadata($entityName)->getTableName();
}
foreach ($schema->getTables() as $table) {
if (in_array($table->getName(), $ignoredTables)) {
$schema->dropTable($table->getName());
}
}
}
}
그리고 이것이 문제를 해결해 줄 뿐만 아니라orm:schema-tool
, 뿐만 아니라 을 위해서도migrations:diff
의doctrine/migrations
모듈.
언급URL : https://stackoverflow.com/questions/8377671/how-to-set-up-entity-doctrine-for-database-view-in-symfony-2
'programing' 카테고리의 다른 글
도커 - 0.0.0.0:4000에 대한 바인딩 실패: 포트가 이미 할당되었습니다. (0) | 2023.09.20 |
---|---|
Build in Docker에서 환경 변수를 설정하는 방법 (0) | 2023.09.20 |
파일 업로드 전 파일 확장명 확인 (0) | 2023.09.20 |
OnclientClick과 OnClick이 동시에 작동하지 않습니까? (0) | 2023.09.15 |
WordPress 설명이 있는 사용자 지정 게시 유형 아카이브 (0) | 2023.09.15 |