Doctrine2 WHERE在可选的JOIN上

时间:2015-02-19 14:54:40

标签: php symfony join doctrine-orm where

这失败

$builder = $repo->createQueryBuilder("ub")
    ->where("ub.badge = :badge AND ub.user = :user AND ub.project = :project")
    ->setMaxResults(1)
    ->setParameter("project", $project)
    ->setParameter("user", $user)
    ->setParameter("badge", $badge);

project可能存在也可能不存在,并导致此错误

  

将实体绑定到查询参数仅允许具有标识符

的实体

如果查询更改为以下内容,它仍然会失败,建议其项目而不是任何其他实体。即使ub(UserBadge)表中没有行,这仍然会失败。

$builder = $userBadgesRepo->createQueryBuilder("ub")
    ->where("ub.project = :project")
    ->setMaxResults(1)
    ->setParameter("project", $project);

如何更改此查询以在WHERE语句中使用project

UserBadge YML

Acme\NameBundle\Entity\UserBadges:
    type: entity
    table: user_badges
    repositoryClass: Acme\NameBundle\Entity\UserBadgesRepository
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO

        added:
            type: datetime

    manyToOne:
        badge:
            targetEntity: Acme\NameBundle\Entity\Badge
            inversedBy: badge_users
            joinColumn:
                onDelete: CASCADE
                name: badge_id
                referencedColumnName: id
        user:
            targetEntity: Acme\NameBundle\Entity\User
            inversedBy: user_badges
            joinColumn:
                onDelete: CASCADE
                name: user_id
                referencedColumnName: id
        project:
            targetEntity: Acme\NameBundle\Entity\Project
            inversedBy: project_badges
            joinColumn:
                onDelete: CASCADE
                name: project_id
                referencedColumnName: id
                nullable: true

Project YML

Acme\NameBundle\Entity\Project:
    type: entity
    table: project
    repositoryClass: Acme\NameBundle\Entity\ProjectRepository
    fields:
        id:
            type: integer
            id: true
            generator:
                strategy: AUTO
**SNIP**

    oneToMany:
         project_badges:
             targetEntity: Acme\NameBundle\Entity\UserBadges
             mappedBy: project

1 个答案:

答案 0 :(得分:2)

这应该有效:

$builder = $repo->createQueryBuilder("ub")
    ->leftJoin('ub.project', 'p')
    ->join('ub.badge', 'b')
    ->join('ub.user', 'u')
    ->where("b.id = :badge AND u.id = :user AND p.id = :project")
    ->setMaxResults(1)
    ->setParameter("project", $project->getId())
    ->setParameter("user", $user->getId())
    ->setParameter("badge", $badge->getId());

解释(摘自评论):

关系是通过引用(id)存储的,你可以直接查询,但不能直接查询对象本身,因为在查询时,sql不知道另一个实体的表。您只能在手动加入关系对象后对其进行比较。

另请阅读第5部分:http://labs.octivi.com/mastering-symfony2-performance-doctrine