我有两个通过一对多单向连接表关联的实体。
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,我像这样重写了我的“查询”,而且它工作正常。
Foo
和 Bar
实体是相同的。
我保留了相同的查询基础,但在 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/