在我的实体中:
/**
* @ORMManyToMany(targetEntity="Productgroup", inversedBy="fields")
* @ORMJoinColumn(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('AppEntityFields', 'f')
->leftJoin('f.productgroup', 'productgroup')
->andWhere('f.productgroup != 6')
->getQuery()
->execute();
}
错误是
无效的路径表达式。StateFieldPathExpression 或 单值关联预期字段
因此,我希望只有组包含horse
.
中->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)
您可以使用 IDENTITY(( DQL 函数跳过左侧连接:
->andWhere('IDENTITY(f.productgroup) != :productgroup_id')
->setParameter('productgroup_id', $id);