【问题标题】:Symfony2 and Doctrine2 : Use a Repository class result in Type classSymfony2 和 Doctrine2 :在 Type 类中使用 Repository 类结果
【发布时间】:2012-11-27 13:20:46
【问题描述】:

我有 5 个实体:

  1. 隶属关系
  2. 用户
  3. 用户隶属关系
  4. 人员隶属关系

我的目标是显示一个选择字段列表,我可以在其中选择所有不在 PersonAffiliations 中的 UserAffiliations。

我的想法是在 UserAffiliationRepository 中创建一个公共函数,它将只返回特定用户的那些从属关系,而不是为特定人预设的。

为此,我正在使用:

class UserAffiliationRepository extends EntityRepository
{ 
   public function getUnselectedAffiliations( $user_id = null, $person_id = null )
   {
      $commQB = $this->createQueryBuilder( 'ua' )
      ->select('ua');

      $commQB->where("ua.user_id = {$user_id}");

      $commQB->andWhere( "ua.affiliation_id not in ( select pa.affiliation_id  FROM SciForumVersion2Bundle:PersonAffiliation pa where pa.person_id = 3077 )" );

      return $commQB->getQuery()->getResult();
   }
}

这很好用。

现在,我想在 FormBuilder 中使用这个结果。为此,在我的控制器中,我正在使用:

$affiliations = $em->getRepository('SciForumVersion2Bundle:UserAffiliation')->getUnselectedAffiliations($user->getId(), $author->getId())
$enquiry    = new PersonAffiliation();
$formType   = new SubmissionAffiliationAddFormType($user, $affiliations);
$form   = $this->createForm($formType, $enquiry);

然后在 Form 类中,我正在使用:

$builder->add('affiliation', 'entity', array(
            'class' => 'SciForumVersion2Bundle:UserAffiliation',
            'multiple' => true));

但是在这里,我得到了特定用户的所有从属关系,而不仅仅是那些尚未在 PersonAffiliations 实体中准备好的那些。

有什么帮助吗?谢谢。

【问题讨论】:

    标签: php symfony doctrine-orm dql


    【解决方案1】:

    您必须通过以下方式将您的 getUnselectedAffiliations 函数直接迁移到 entity_type 中

    $builder->add('affiliation', 'entity', array(
                'class' => 'SciForumVersion2Bundle:UserAffiliation',
                'multiple' => true,
                'query_builder' = function(EntityRepository $repo) use ($yourParameters){
                                   return $repo->createQueryBuilder(....);}));
    

    如果你想传递$yourParameters,你必须把它传递到__construct函数中(实现它,如果你没有),当你创建你的表单时,你可以在调用中传递它们

    【讨论】:

    • 谢谢@DonCallisto。是的,我有 _construct 函数,并且能够获取所有需要的参数。我现在就试试你的解决方案。
    • 嗯,第一个问题,如何访问 entity_type 类中的getUnselectedAffiliations ?我应该在 createQueryBuilder(....) 中添加什么谢谢
    • @Milos 您不能直接将其访问到 entity_type:您必须将您拥有的代码移动到该函数中 createQuerybuilder(....) [替换点]
    • 啊好吧,实体类型里直接访问repository查询不就行了吗?
    • @Milos 我忽略了这种可能性。我想如果教程说您必须编写 DQL 或将 QueryBuilder 直接构建到您的 entity_type 中,也许这是唯一也是最好的解决方案。但我不能打赌:)(你有没有在其他地方重用这段代码?)
    猜你喜欢
    • 1970-01-01
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2012-06-19
    • 2023-03-29
    • 1970-01-01
    相关资源
    最近更新 更多