如何通过相关id(Symfony 4)过滤学说查询?

问题描述 投票:0回答:1

在我的实体中:

  /**
  * @ORM\ManyToMany(targetEntity="Productgroup", inversedBy="fields")
  * @ORM\JoinColumn(name="productgroup", referencedColumnName="id")
  */
  private $productgroup;

  public function getProductgroup()
  {
    return $this->productgroup;
  }

  public function setProductgroup($productgroup): self
  {
    $this->productgroup = $productgroup;

    return $this;
  }

  public function __construct()
  {
    $this->productgroup = new ArrayCollection();
  }

在我的控制器中:

$group = $this->getDoctrine()->getRepository(class::fields)->findAll();

输出:

array:2 [▼
  0 => Fields {#120842 ▼
    -id: 3
    -name: "cat"
    -unique_id: "5a38c820ed"
    -productgroup: PersistentCollection {#120846 ▼
      -snapshot: array:1 [ …1]
      -owner: Fields {#120842}
      -association: array:20 [ …20]
      -em: EntityManager {#114768 …11}
      -backRefFieldName: "fields"
      -typeClass: ClassMetadata {#119877 …}
      -isDirty: false
      #collection: ArrayCollection {#120847 ▼
        -elements: array:1 [▼
          0 => Productgroup {#120528 ▼
            -id: 6
            -name: "Animals"
            -unique_id: "9e4ef1c46f"
            -fields: PersistentCollection {#120739 ▶}
          }
        ]
      }
      #initialized: true
    }
    -type: Type {#120923 ▶}
  }
  1 => Fields {#120924 ▼
    -id: 5
    -name: "horse"
    -unique_id: "c3890b9287"
    -productgroup: PersistentCollection {#120925 ▼
      -snapshot: []
      -owner: Fields {#120924}
      -association: array:20 [ …20]
      -em: EntityManager {#114768 …11}
      -backRefFieldName: "fields"
      -typeClass: ClassMetadata {#119877 …}
      -isDirty: false
      #collection: ArrayCollection {#120926 ▼
        -elements: []
      }
      #initialized: false
    }
    -type: Type {#120927 ▶}
  }
]

我想现在过滤所有$group,只输出没有连接到产品组的字段,其id为6。我的方法:

在我的控制器中:

$group = $this->getDoctrine()->getRepository(class:fields)->filterByColletion(6);

在我的存储库中:

 public function filterByColletion($id)
    {
      return $this->createQueryBuilder('p')
      ->addSelect('f')
      ->from('App\Entity\Fields', 'f')
      ->leftJoin('f.productgroup', 'productgroup')
      ->andWhere('f.productgroup != 6')
      ->getQuery()
      ->execute();
    }

错误是

无效的PathExpression。期望StateFieldPathExpression或SingleValuedAssociationField

因此,我预计只有组包含horse

symfony filter doctrine arraycollection
1个回答
1
投票

你的查询中有->andWhere('f.productgroup != 6'),但f.productgroup不是普通的值字段,而是关系。你需要将你的条件应用于值字段,所以它会是这样的:

->leftJoin('f.productgroup', 'pg')
->andWhere('pg.id != 6')

我在这个例子中使用过pg.id,但你需要使用你要应用条件的Productgroup实体的实际值字段名称。

附注:最好不要将值直接嵌入到查询中,而是将其作为参数传递:

->leftJoin('f.productgroup', 'pg')
->andWhere('pg.id != :id')
->setParameter(':id', 6)
© www.soinside.com 2019 - 2024. All rights reserved.