How to set up entity (doctrine) for database view in Symfony 2
The accepted answer is correct, but I'd like to offer some additional suggestions that you might want to consider:
Mark your entity as read-only.
Make the constructor private so that only Doctrine can create instances.
/** * @ORM\Entity(readOnly=true) * @ORM\Table(name="your_view_table") */class YourEntity { private function __construct() {}}
There is nothing special in querying a view — it's just a virtual table. Set the table of your entity this way and enjoy:
/** * @ORM\Entity * @ORM\Table(name="your_view_table") */class YourEntity { // ...}
Both the previous answers are correct, but if you use the doctrine migration tool and do a schema:update
it will fail...
So, in addition to marking the entity as read only and making the constructor private (explained in Ian Phillips answer):
/** * @ORM\Entity(readOnly=true) * @ORM\Table(name="your_view_table") */class YourEntity { private function __construct() {}}
You would need to set the schema tool to ignore the entity when doing a schema:update...
In order to do that you just need to create this command in your bundle, and set yout entity in the ignoredEntity list:
src/Acme/CoreBundle/Command/DoctrineUpdateCommand.php:
<?phpnamespace 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); }}
(credit to Alexandru Trandafir Catalin: obtained from here: https://stackoverflow.com/a/25948910/1442457)
BTW, this is the only way I found to work with views from doctrine... I know it is a workaround... If there is a better way I am open or suggestions)