Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 rejecting my custom findBy function in my model class

I followed the example of setting up a custom findOneByJoinedToCategory($id) function in the Doctrine model class as explained in the documentation here:

http://symfony.com/doc/current/book/doctrine.html

In my case, I have a model class called TestVendorCategory containing a bunch of attributes and this function:

public function findOneByNameJoinedToVendorCategoryMappings($vendorCategoryName)
    {
        $query = $this->getEntityManager()
        ->createQuery('
                SELECT vc, vcm FROM TestCoreBundle:VendorCategory vc
                JOIN vcm.vendorCategoryMapping vcm
                WHERE vc.name = :name'
        )->setParameter('name', $vendorCategoryName);

        try
        {
            return $query->getSingleResult();
        }
        catch (\Doctrine\ORM\NoResultException $e)
        {
            return null;
        }
    }

In my controller, I call it like this:

$vendorCategoryMapping = $this->em->getRepository("TestCoreBundle:VendorCategory")->findOneByNameJoinedToVendorCategoryMappings($vendorCategoryName);

When I go to the browser and execute this action with this call in it, I get the following error message:

Entity 'Test\CoreBundle\Entity\VendorCategory' has no field 'nameJoinedToVendorCategoryMappings'. You can therefore not call 'findOneByNameJoinedToVendorCategoryMappings' on the entities' repository

It looks like Symfony 2.1 wants the findOneBy...() methods to reflect names of existing fields only, no custom "JoinedTo..." kinds of methods. Am I missing something, please? The documentation shows an example like this where it supposedly works. I am using annotations, but this method doesn't have any. Thank you!

like image 914
pkout Avatar asked Mar 02 '13 22:03

pkout


1 Answers

You have to put the findOneByNameJoinedToVendorCategoryMappings function in the VendorCategoryRepository class:

<?php
namespace Test\CoreBundle\Entity;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\NoResultException;

class VendorCategoryRepository extends EntityRepository
{
    public function findOneByNameJoinedToVendorCategoryMappings($vendorCategoryName)
    {
        $query = $this->getEntityManager()
            ->createQuery('
            SELECT vc, vcm FROM TestCoreBundle:VendorCategory vc
            JOIN vcm.vendorCategoryMapping vcm
            WHERE vc.name = :name'
        )->setParameter('name', $vendorCategoryName);

        try
        {
            return $query->getSingleResult();
        }
        catch (NoResultException $e)
        {
            return null;
        }
    }
}

and link this repository class in the Entity:

/**
 * @ORM\Entity(repositoryClass="Test\CoreBundle\Entity\VendorCategoryRepository")
 */
class VendorCategory
like image 148
hacfi Avatar answered Sep 28 '22 03:09

hacfi