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 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型