Question

I have a book and an author tables I configured like this in symfony 2 :

author.orm.yml :

Author:
    type: entity
    table: null
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        firstname:
            type: string
            length: '255'
        lastname:
            type: string
            length: '255'
    lifecycleCallbacks: {  }

book.orm.yml

Book:
    type: entity
    table: null
    id:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
    fields:
        title:
            type: string
            length: 255
    manyToOne:
        verbatim:
            targetEntity: Author
            joinColumn:
                onDelete: CASCADE
    lifecycleCallbacks: {  }

Is it possible to have a method in my Author Entity to get all it's books.

Example :

/** @var Author $author */
$author = $em->getRepository('Author')->findOne();

/** @var Book[] $bookList */
$bookList = $author->getAllBooks()

I wanted to create such a method in my Entity but evebody swears god EntityManager shall not be accesed from an Entity.

What do you think about it ?

Regards

FIX :

added in my author.orm.yml:

oneToMany:
    page:
        targetEntity: Book
        mappedBy: book

Thanks a lot @metalvarez

Was it helpful?

Solution

I think you need a many to one bidirectional relationship, check this question Doctrine should find all your books, you just need to create your getters and setters for your books property in your author entity and let doctrine do the rest.

OTHER TIPS

You need to create EntityRepositories and put your functions for this entity there. The Entity class should provide nothing more than the variables (which stand for the columns) and the getter and setters.

In the controller you can do something like this

$em = $this->getManager()->getRepository('Path\To\Your\Entity\'); 
$books = $em->getAllBooksByAuthorId($id);

The function "getAllBookgsByAuthorId" would be implemented in the RepositoryClass

class BookRepository extends Doctrine\ORM\EntityRepository{

public function getAllBooksByAuthorId($id){
     $qb = $this->createQueryBuilder('b')
                ->select()
                ->where('authorId = ' . $id);

    return $qb->getQuery()->getResult();
    }
}

More Information here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top