数组映射关系一对多怎么解决 php,symfony中使用Doctrine一对多映射在取对应Entity数组时的如何先排序?...

解决方案如下:

修改Person类的getChildren方法

// src/AppBundle/Entity/Person.php

// ...

use Doctrine\Common\Collections\Criteria;

//...

/**

* @param string $orderedByAge "ASC"|"DESC"

*/

public function getChildren($orderedByAge=null)

{

if (null === $orderedByAge) {

return $this->children;

}

if (!in_array(strtoupper($orderedByAge), ['ASC', 'DESC'])) {

throw new \InvalidArgumentException('参数错误,必须是"ASC"或"DESC"中的一个');

}

$order = 'ASC' === $orderedByAge ? Criteria::ASC : Criteria::DESC;

$criteria = Criteria::create()->orderBy(['age' => $order]);

return $this->children->matching($criteria);

}

// ...

如果不想修改getChildren方法,可以写一个新的方法getChildrenOrderedByAge,道理同上。

总结:

Doctrine的一对多或者多对多关系中,Entity中所谓多的属性是Doctrine\Common\Collections\Collection接口的某一实现的实例,默认情况下是Doctrine\Common\Collections\ArrayCollection,上述解决方案中用到的就是这一接口的Filtering API(筛选接口),上述情况下,筛选的条件会最终转化到SQL层进行处理,以达到性能优化的目的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值