简体   繁体   中英

Query builder cannot associate with category entity

I have 2 entities, MyItem and MyItemCategory. When I try to create a query with query builder I get the following error:

Error: Class App\Entity\MyItem has no
    field or association named myitem_category_id (500 Internal Server Error)

This is the where part of my query builder:

$queryBuilder = $this->getDoctrine()
        ->getRepository('App\Entity\MyItem')
        ->createQueryBuilder('m');

// adds where for category_id:
$queryBuilder->where('m.myitem_category_id = :category_id')->setParameter('category_id',$category_id);

Here're first entities:

/**
 * @ManyToOne(targetEntity="MyItemCategory")
 * @JoinColumn(name="myitem_category_id", referencedColumnName="id")
 */
private $myItemCategory;

...and my category entity:

/**
 * @ORM\OneToMany(targetEntity="MyItem", mappedBy="myItemCategory")
 */
private $myItemCategories;

The querybuilder actually doesn't care about database fields, but instead uses the object mapper, so there is no field my_item_category_id on your Entity , but instead a field myItemCategory

So, you can either do:

$querybuilder
    ->where('m.myItemCategory = :category')
    ->setParameter('category', $category) // <-- an actual MyItemCategory object

or you can join it in and check for the id:

$querybuilder
    ->leftJoin('m.myItemCategory', 'mic')
    ->where('mic.id = :micid')
    ->setParameter('micid', $category_id)

(I actually don't know if m.myItemCategory.id = :micid might work ........ you could try ;o))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM