dougui5419 2015-03-05 21:14
浏览 20

Doctrine - 如果用户实体可以有一个或多个地址,如何通过用户实体访问用户的活动地址?

I have a User and Address entity. A user can have many Addresses, but only one of them can be marked as active.

I want the User entity to have a property that is $activeAddress which would contain an Address. In other words, getActiveAddress() would return an Address object.

Is there a way to set up an annotation to do this similar to a one to one annotation? This is essentially a one to one relationship as long as we are able to enforce a filter.

So for User with an id of 5:

SELECT * FROM address WHERE active = 1 AND user_id = 5 LIMIT 1;

This would always return the active address. How do I set up my User entity to reflect this?

  • 写回答

1条回答 默认 最新

  • douhan4243 2015-03-05 22:00
    关注

    You could use the collection criteria API which allows you to transparently filter collections. Doctrine will trigger either a SQL query or filter the in memory association when it is already loaded.

    public function getActiveAddress()
    {
        $criteria = Criteria::create()
            ->where(Criteria::expr()->eq("active", true))
            ->setMaxResults(1);
    
        $addresses = $this->addresses->matching($criteria);
        if ($addresses->count() == 1) {
            return $addresses->current();
        }
        return null;
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?