php - Doctrine 在一对多单向连接表中查询一个实体

标签 php symfony doctrine-orm

我有两个通过一对多单向连接表关联的实体。

use Doctrine\ORM\Mapping as ORM;

/**
 * @Entity(repositoryClass="FooRepository")
 */
class Foo
{
    /**
     * @var Collection
     * @ORM\ManyToMany(targetEntity="Bar")
     * @ORM\JoinTable(
     *      name="foo_bar",
     *      inverseJoinColumns={@ORM\JoinColumn(unique=true)}
     * )
     */
    private $bars;

    /**
     * @var int
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    // [...]
}
/**
 * @Entity(repositoryClass="BarRepository")
 */
class Bar
{
    /**
     * @var int
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    // [...]
}

我想使用返回一个或空 Bar 对象的 foo id 和 bar id 在我的 BarRepository 类中创建一个方法。

实际上我的类(class)是这样的:

use Doctrine\ORM\EntityRepository;

class BarRepository extends EntityRepository
{
    /**
     * Finds a single bar.
     * @param int $fooId The foo identifier.
     * @param int $barId The bar identifier.
     * @return Bar|null
     */
    public function findOneByFoo($fooId, $barId)
    {
        $qb = $this->createQueryBuilder('b');
        $qb->innerJoin('Foo', 'f', Expr\Join::WITH, 'f.id = :fooId')
        ->where('b.id = :barId')
        ->setParameter('fooId', $fooId)
        ->setParameter('barId', $barId)
        ->getQuery()->getOneOrNullResult();
    }
}

但这总是返回一个 bar 对象,即使 bar id 没有关联到 foo 对象。

最佳答案

好吧,多亏了 staskrak,我像这样重写了我的“查询”,而且它工作正常。 FooBar 实体是相同的。 我保留了相同的查询基础,但在 Foo->bars 属性和 Bar 实体之间添加了一个内部连接。

use Doctrine\ORM\EntityRepository;

class BarRepository extends EntityRepository
{
    public function findOneByFoo($fooId, $barId)
    {
        $parameters = [
            ':fooId' => $fooId,
            ':barId' => $barId
        ];
        $qb = $this->createQueryBuilder('b');
        return $qb
            ->innerJoin('Foo',    'f',  'WITH', 'f.id = :fooId')
            // below, the added inner join
            // it makes the link between the Foo->bars property and the Bar entity
            ->innerJoin('f.bars', 'fb', 'WITH', 'b.id = fb.id')
            ->where('b.id = :barId')
            ->setParameters($parameters)
            ->getQuery()
            ->getOneOrNullResult();
    }
}

关于php - Doctrine 在一对多单向连接表中查询一个实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45511924/

相关文章:

javascript - 如何在单击按钮时从 javascript 函数调用 ajax?

php - 如何为 unicode 标题创建 unicode slug?

php - 无法让 Python 3 将 POST 数据传输到 PHP

php - 如何将时间(秒)与名称相关联

php - 通过服务将 Symfony EntityManager 注入(inject)到表单类型中

doctrine-orm - 带有连接表的 Doctrine 2 ManyToOne

doctrine-orm - Symfony2 : File Upload via Doctrine does not fire the PrePersist/PreUpdate lifecycle-event

php - 如何在 symfony2 而不是异常页面中显示有关删除父节点的警告消息?

php - Doctrine 实体管理器通过空数组集合查找

php - 如果服务器离线,如何告诉 Doctrine 忽略 Memcached?