0

在引用和销售绘画的 symfony2 应用程序中,我有两个对象:

  • 所有的画都是绘画的实例
  • 其中一些是待售的,我将拍卖实例与它们相关联

两者之间存在 OneToMany 关系,由绘画映射

我的问题 :

// In Controller.php  
public function homepageListAction()
{

    $paintings = $this->getPaintingRepository()->findPaintingsForHomepage();
    $auctions  = $this->getPaintingRepository()->findAuctionsForHomepage();

    foreach($paintings as $painting) 
    { 
        $painting->setAboutText(substr($painting->getAboutText(), 0, 150) . '...');
        // This works 
    }

    foreach($auctions as $auction)
    {
        $auction->setAboutText(substr($auction->getAboutText(), 0, 150) . '...');
        // Error : using a member property on a non-object
    }

    // Rest of function

通过一些调试,似乎$paintings是一个对象数组,而$auctions是一个数组数组,包含拍卖的数据和与之关联的绘画。因此,我可以轻松访问与拍卖相关的绘画数据,但在将其发送到我的模板之前,我不知道如何以直接的方式对其进行操作。

我的问题 :

  • 如何从我的数据库中获取拍卖作为对象而不是数组?
    或者
  • 如何允许我的拍卖访问控制器内的绘画获取器/设置器?

各种信息:

数据库配置(学说)

Painting ORM
oneToMany:
    painting:
        targetEntity: Auction
        mappedBy: Painting


Auction ORM
manyToOne:
    Painting:
        targetEntity: Painting
        inversedBy: auction
        joinColumn:
            name: painting_id
            referencedColumnName: id
            onDelete: SET NULL

实体(摘录)

//painting.php

/**
 * @var text $about_text
 */
private $about_text;

/**
 * Set about_text
 *
 * @param text $aboutText
 */
public function setAboutText($aboutText)
{
    $this->about_text = $aboutText;
}

/**
 * Get about_text
 *
 * @return text 
 */
public function getAboutText()
{
    return $this->about_text;
}

//auction.php

/**
 * @var my\bundle\Entity\Painting
 */
private $Painting;

 /**
 * Set Painting
 *
 * @param my\bundle\Entity\Painting $painting
 */
public function setPainting(\my\bundle\Entity\Painting $painting)
{
    $this->Painting = $painting;
}

/**
 * Get Painting
 *
 * @return my\bundle\Entity\Painting
 */
public function getPainting()
{
    return $this->Painting;
}

查询(都在 PaintingRepository.php 中)

public function findPaintingsForHomepage()
{

    $queryBuilder = $this->getEntityManager()->createQueryBuilder('m');

    return $queryBuilder->select('m')
            ->from('MyBundle:Painting', 'm INDEX BY m.id')
            ->orderBy('m.updated_at', 'DESC')
            ->getQuery()
            ->execute()
    ;
}

public function findAuctionsForHomepage()
{
    $sql = 
    <<<EOF

        SELECT p.*, 
            (a.amount) as auction_amount,
        FROM painting p

        LEFT JOIN auction a
            ON p.id = a.painting_id
        WHERE a.state IS NOT NULL
    EOF
    ;    
    $stmt = $this->getEntityManager()->getConnection()->prepare($sql);
    $stmt->execute();
    $result = $stmt->fetchAll();

    return $result;
}
4

1 回答 1

0

您需要将普通查询结果映射到学说实体对象。阅读本机查询

    $em = $this->getEntityManager();
    $rsm = new \Doctrine\ORM\Query\ResultSetMappingBuilder($em);
    $rsm->addRootEntityFromClassMetadata('my\bundle\Entity\Painting', 'p');
于 2013-07-04T13:45:20.767 回答