Doctrine2 findBy relationship object triggers string conversion error

后端 未结 3 922
遥遥无期
遥遥无期 2020-12-05 18:49

Say I have two entities in Doctrine2 that are related to each other, Models\\User and Models\\Comment. If I do this in Doctrine 2.0.0...



        
相关标签:
3条回答
  • 2020-12-05 18:56

    For symfony 4.1 this code worked for me.

    $comments = $this->getDoctrine()
                    ->getRepository(Models\Comment::class)
                    ->findBy(
                    ['user' => $user->getId(), 'public' => true]
    );
    
    0 讨论(0)
  • 2020-12-05 19:04

    Query by relationship is allowed, but you have to pass the Identifier in there. Query by object is not yet supported and will only make it into 2.1.

    <?php
    // $em instanceof EntityManager, $user instanceof Models\User
    $comments = $em->getRepository('Models\Comment')
    ->findBy(array('user' => $user->getId(), 'public' => true));
    
    0 讨论(0)
  • 2020-12-05 19:08

    Unfortunately, I don't think query by relationships is supported directly via repository objects.

    In this case, you are probably best to write a custom repository class with a findByUser method.

    <?php
    
    namespace App\Domain\Repository;
    
    use Doctrine\ORM\EntityRepository,
        App\Domain\Entity\User;
    
    class CommentRepository extends EntityRepository
    {
    
        public function findByUser(User $user)
        {
            // add QueryBuilder code here
        }
    
    }
    

    Don't forget to update your Comment entity to use the custom repository:

    <?php
    
    namespace App\Domain\Entity;
    
    
    /** 
     * @Entity(repositoryClass="App\Domain\Repository\CommentRepository")
     */
    class Comment 
    {
    
        // entity definition
    
    }
    
    0 讨论(0)
提交回复
热议问题