duanbo19834 2014-08-09 20:28
浏览 21
已采纳

为连接的doctrine 2集合实现getter

I'm trying to create simple getter methods in original entity for specific item in doctrine collection of joined entity.

Main entity looks something like this:

class Product
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

...

/**
 * @ORM\OneToMany(targetEntity="File", mappedBy="product")
 */
private $files;

}

And joined entity:

class PrankFile
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\ManyToOne(targetEntity="Product", inversedBy="files")
 * @ORM\JoinColumn(name="product_id", referencedColumnName="id", onDelete="CASCADE")
 */
protected $product;

/**
 * @var string
 *
 * @ORM\Column(name="type", type="string", length=16)
 */
private $type;  

...

My DQL in repository class is very simple:

    return $this->getEntityManager()
        ->createQuery('SELECT p, f FROM AppProductBundle:Product p INNER JOIN p.files f ORDER BY p.created DESC')
        ->setMaxResults($limit)
        ->getResult();

In files entity type field tells me what kind of a file is it (image, sound, video, demo etc...) Problem comes when I wish to print out a list of all products and display image next to product details, I would hate to loop through product files for each product displayed.

Is it possible to create some simple getter on product entity to fetch file of certain type? Or maybe it would be better to create more complex DQL query for this, again how to do this?

I can't just fetch image record from files in DQL because I need all files for certain products.

Any help with this would be most welcome.

  • 写回答

1条回答 默认 最新

  • duanlongnao0028 2014-08-10 08:54
    关注

    You can filter directly on collections using the filter api. If the collection is not loaded already Doctrine will apply your filter on a SQL level, giving you max performance. In case the collection is already eager loaded Doctrine will filter the ArrayCollection in memory.

    use Doctrine\Common\Collections\Criteria;
    
    class Product
    {
        public function getFilesByType($type)
        {
            $criteria = Criteria::create()
                ->where(Criteria::expr()->eq("type", $type))
            return $this->files->matching($criteria);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址