3
在Doctrine2中發出查詢之前,是否可以檢查關聯是否存在?例如:檢查在Doctrine2中是否存在沒有捕獲異常的關聯?
/**
* @ORM\Entity
*/
class Product
{
/**
* @ORM\OneToMany(targetEntity="Feature", inversedBy="product")
*/
public $features;
}
我想檢查(實際上沒有發出查詢本身),它的關聯product.features
存在。
編輯:出於好奇,我正在寫一個服務(一個幫手,真)做基於GET paramters一些收集過濾:
public function initialize($entityName, $key)
{
// Defaults are empty values and empty collection
$this->values = array();
$this->collection = new ArrayCollection();
// If "$key" GET parameter is null or blank return this instance
if(is_null($value = $this->request->get($key))
|| strlen(trim($value)) == 0) return $this;
// Split the parameter value based on separator (typically a comma)
$re = '/\s*' . $this->separator . '\s*/';
// Return this instance if no values are found
if(!($set = preg_split($re, $value, 0, PREG_SPLIT_NO_EMPTY))) return $this;
// Guess the repository fully qualified name and entity name
$guesser = $this->getManagementGuesser();
$repoName = $guesser->guessRepositoryName();
$entityName = $guesser->guessEntityName();
// Get the repository for the entity and create the builder
$qb = $this->getRepository($repoName)->createQueryBuilder('e');
// Check if a relation named $key exists and throw a LogicException
$exists = $this->getEntitiesUtility()->checkRelation($entityName, $key);
if(!$exists) throw new \LogicException("Relation named '$key' not found.");
// Other stuff
}
的初步認識部分是:
$this->getEntitiesUtility()->checkRelation($entityName, $relationName);
您的意思是指給定的產品是否至少有一個關聯的功能記錄?您*有*執行查詢來做到這一點。 –
@PeterBailey不,我知道我可以內心加入它。我在說如果產品實際上有一個名爲「功能」的關係。 – Polmonino
獲取類元數據並通過它循環以檢查實體中是否定義了這種關係。不過,我會進一步知道你爲什麼問這個問題,因爲我懷疑你正在試圖解決這樣的多態問題或類似的問題,如果你是這樣的話有更好的方法。 –