学说2.如何从表中只获得一列?

时间:2014-05-13 06:29:26

标签: symfony doctrine-orm

我有这个实体:

class TruckOrderPud {
/**
 * @ORM\Id     
 * @ORM\OneToOne(targetEntity="Pud")
 * @ORM\JoinColumn(name="pud_id", referencedColumnName="id", onDelete="CASCADE")
 */
protected $pudId;

/**
 * @ORM\Id
 * @ORM\OneToOne(targetEntity="TruckOrder")
 * @ORM\JoinColumn(name="truck_order_id", referencedColumnName="id", onDelete="CASCADE")
 */
protected $truckOrderId;

/**
 * @ORM\Column(name="package_count", type="integer", options={"unsigned"=true}, nullable=true)
 */
protected $packageCount;

/**
 * @ORM\Column(name="package_weight", type="integer", options={"unsigned"=true}, nullable=true)
 */
protected $packageWeight;

}

我需要通过pudId参数从此实体中获取单列truckOrderId

我试试:

   $result = $this->_em->createQuery('SELECT top.pudId FROM AppTruckingBundle:TruckOrderPud top WHERE top.truckOrderId = ?1')
                    ->setParameter(1, $truckOrderId)
                    ->getSQL();`

然后我有错误:

"[Semantical Error] line 0, col 11 near 'pudId FROM AppTruckingBundle:TruckOrderPud': Error: Invalid PathExpression. Must be a StateFieldPathExpression."

如果我在'SELECT top.pudId...'上更改了'SELECT top...'的查询,那一切都没问题。

我也试试:

    $qb = $this->_em->createQueryBuilder();

    $qb->select('top.pudId')
                 ->from('AppTruckingBundle:TruckOrderPud', 'top')
                 ->where($qb->expr()->eq('top.truckOrderId', $truckOrderId));`

在这种情况下,我得到了相同的错误。如果我在$qb->select('top.pudId')上更改$qb->select('top'),一切正常。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

PudId是一个引用Pud的外键,所以你必须参考Pud。试试这个

$qb->select('IDENTITY(top.pud) PudId')
->from('AppTruckingBundle:TruckOrderPud', 'top')
->where($qb->expr()->eq('top.truckOrderId', $truckOrderId));`

答案 1 :(得分:0)

尝试从1中移除?1,只留下?

   $result = $this->_em->createQuery('SELECT top.pudId FROM AppTruckingBundle:TruckOrderPud top WHERE top.truckOrderId = ?')
                    ->setParameter(1, $truckOrderId)
                    ->getSQL();

Doctrine自行完成参数定位(第一个问号点上的第一个参数)。请阅读here了解详情。