【问题标题】:How to make multiple table connections in symfony2 Repository ? Entity?如何在 symfony2 Repository 中建立多个表连接?实体?
【发布时间】:2018-03-02 18:36:18
【问题描述】:

我有类似的桌子 profilestatus

Profile.class

id name
1  taro
2  jiro
3  john

状态类

id profile school           date
1  1       highschool       2017-04-01
2  1       juniorhighschool 2013-04-01
3  2       highschool       2017-04-01

状态改变时添加状态。

所以我通常每次需要状态时都会选择最新状态。

$ss = $this->em->createQuery(
  "SELECT cm FROM UserBundle:Status s where c.profile = :p order by desc")                 
                ->setParameters(['p' => $profile])->getResult();
$ss[0] // Latest Status

所以现在我想把它放在函数中。

我想做的是从个人资料中获取最新状态。

我有一些想法

  • 把这个函数放在 Profile Entity 中?
  • 将此函数放入配置文件存储库?
  • 将此功能投入使用???

在我看来它应该是 Profile Entity 的功能,所以我想把它放在 Entity 中,从 Entity 访问另一个是不好的方式。

可以从 Profile Repository 访问另一个实体吗?

或者我应该使用服务吗??

【问题讨论】:

  • 完全可以接受配置文件存储库返回状态实体。

标签: symfony repository entity


【解决方案1】:

您可以通过 ProfileRepository 中的方法实现此目的

<?php

public function getLastStatusByProfile(Profile $profile)
{
  // do our query from Profile with a join on Status
}

请在查询中使用 LIMIT 1,您只需要最后一个结果

【讨论】:

    【解决方案2】:

    您不能将其放入实体中,因为实体无法注入 Doctrine EntityManager 依赖项 ($this-&gt;em)。 要执行“getLatestStatus()”函数,您需要 EntityManager $this-&gt;em

    要访问 EntityManager,您可以:

    通常人们将诸如getLatestStatus() 之类的函数放在存储库中,存储库变成“我们放置所有 DQL 查询的类”,这工作得很好。这是官方文档 (https://symfony.com/doc/current/doctrine/repository.html) 推荐的“然后可以将包含查询逻辑的方法存储在此类中。”

    在 Symfony 应用程序中通常有:

    • 只有属性、getter、setter 和一些附加逻辑函数的实体(如 activate()disable() ... 修改实体属性的函数)

    • 用于保存具有复杂逻辑的 DQL 查询的存储库,例如 getLatestStatus()

    • 用于保存读取/修改数据的其他任何其他功能的服务

    • 控制器只是使用服务的网关

    所以一个完整的例子是:

    <?php
    
    class ProfileRepository extends EntityRepository
    {
        /**
         * @param Profile $profile 
         *
         * @return Status
         */
        public function getLatestStatus($profile)
        {
            $qb = $this->getEntityManager()->createQuery(
            "SELECT cm FROM UserBundle:Status s where c.profile = :p order by desc")                 
                    ->setParameters(['p' => $profile])
                    ->getResult();
    
            return $result;
        }
    }
    

    并且不要忘记处理此配置文件没有“状态”可用的情况。您希望返回null、引发异常还是返回默认status

    【讨论】:

      猜你喜欢
      • 2022-09-30
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多