Symfony表单集合OrderBy来自ManyToOne的OneToMany关系字段

时间:2015-10-30 14:37:16

标签: symfony symfony-forms

有点棘手:

我有一个实体Street的表单集合。 集合项是houses。我需要通过room

订购集合中的房屋

我曾尝试添加@ORM\OrderBy({"room" = "ASC"}),但显然没有在房间实体内指定权重字段,集合无法知道。

我想做的甚至可能吗?

Street.php

/**
 * @var ArrayCollection
 *
 * @ORM\OneToMany(targetEntity="houses", mappedBy="street")
 */
protected $houses;

Houses.php

/**
 * @var Room
 *
 * @ORM\ManyToOne(targetEntity="Room", inversedBy="house")
 * @ORM\JoinColumn(name="room_id", referencedColumnName="id")
 */
private $room;

/**
 * @var Street
 *
 * @ORM\ManyToOne(targetEntity="Street", inversedBy="houses")
 * @ORM\JoinColumn(name="street_id", referencedColumnName="id")
 */
private $street;

HouseCollectionType.php

 $builder
        ->add('houses', 'collection', array(
            'type'          => new HouseFieldsType(),
            'allow_delete'  => false,
        ))
    ;

 public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
    $resolver->setDefaults(array(
        'data_class' => 'Bundle/Street'
    ));
    }

1 个答案:

答案 0 :(得分:-1)

我不知道这是不是正确的方法,但在这里:

Street.php

public function getHouses()
{
    $orderedHouse = array();
    /** @var House $house */
    foreach($this->houses as $house) {
        $orderedHouses[$house->getRoom()->getWeight()] = $house;
        $this->houses->removeElement($house);
    }
    ksort($orderedHouses);
    foreach($orderedHouses as $house) {
        $this->houses->add($house);
    }
    return $this->houses;
}