mohamad ali gharat
mohamad ali gharat

Reputation: 501

how and where to execute custom queries in symfony 4

I am using an entity class which extends ServiceEntityRepository like this:

class Sms extends ServiceEntityRepository
{ 
   public function __construct(ManagerRegistry $registry)
   {
       parent::__construct($registry, Sms::class);
   }
... 
}

so when I need to persist an instance of the entity class in my controller file I need to pass the ManagerRegistry as the argument for my Entity class but I couldn't find a way to access the ManagerRegistry in my controller.

can anyone help?

Upvotes: 0

Views: 719

Answers (1)

mohamad ali gharat
mohamad ali gharat

Reputation: 501

The problem was that ServiceEntityRepository should be extended in a repository class, not an entity class. as it is mentioned here, there is no good description for auto-generating repositories from an existing database. This is my entity class with its annotations:

/**
* Sms
*
* @ORM\Table(name="sms")
* @ORM\Entity(repositoryClass="App\Repository\SMSRepository")
 */
class Sms
{ ... }

this line is very important: @ORM\Entity(repositoryClass="App\Repository\SMSRepository")

another important thing is to removing Entity from excluding in the services.YAML file.

if you set a name for the repository of your entity class by annotation, by running this command you will have your repository generated:

php bin\console make:entity --regenerate

and you can simply write you complex queries in the repository file which is generated by the aforementioned command.

for calling methods of your repository class you can use this in your controller files:

$this->getDoctrine()->getRepository(EntityFile::class)->youFunctionNameInRepositoryFile()

be careful about the argument of the getRepository which is the Entity file, not the repository file.

Upvotes: 1

Related Questions