在Symfony / Doctrine中使用外键作为参数

时间:2012-11-30 10:09:01

标签: symfony doctrine-orm foreign-keys

我对symfony / Doctrine很新,并且在querybuilder上遇到了一些问题:

鉴于此ER:

ER

以下声明:

namespace xxx\SeoBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * xxx\SeoBundle\Entity\Session
 *
 * @ORM\Table(name="session")
 * @ORM\Entity
 */
class Session
{
    const repositoryName = "InternetSmSeoBundle:Session";

    /**
     * @var string $id
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     */
    private $id;
......
    /**
     * @var Gsite
     *
     * @ORM\ManyToOne(targetEntity="Gsite")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="gsite_id", referencedColumnName="id")
     * })
     */
    private $site;
......
}

我需要找到按网站过滤的会话。 我尝试过以下方法:

    $rep = $this->em->getRepository(Session::repositoryName);
    $qb = $rep->createQueryBuilder("s");

    $qb->setMaxResults(200);
    $qb->where("1=1");
    $qb->orderBy("time", "desc");

    //site
    if ($params->site != null){
        /** @var Gsite **/
        $site = $params->site;
        $qb->where($qb->expr()->eq("gsite_id",$site->getId()));
    }

甚至

    $qb->where($qb->expr()->eq("site",$site));

但它不起作用。在存在多对一外键的情况下过滤数据的正确方法是什么?我是否需要在模型中创建gsite_id列的声明?

感谢。

1 个答案:

答案 0 :(得分:2)

设置参数,Doctrine将能够推断出类型(不需要使用外键id):

$qb
    ->where($qb->expr()->eq('site', ':site'))
    ->setParameter('site', $site);
;
相关问题