我與Symfony的2.3工作的聯繫和學說1.2添加屬性子實體與學說的QueryBuilder的
我有以下實體結構,產品,標籤和TagCategory。產品具有與Tag多對多的關係,標籤與TagCategory
產品一流的多對一的關係:
class Product
{
/**
* @var ArrayCollection List of tags
*
* @ORM\ManyToMany(targetEntity="Tag", inversedBy="products")
* @ORM\JoinTable(name="tags_productos",
* joinColumns={@ORM\JoinColumn(name="cod_pro", referencedColumnName="cod_pro")},
* inverseJoinColumns={@ORM\JoinColumn(name="cod_tag", referencedColumnName="id")}
* )
*/
protected $tags;
}
TagCategory類:
class TagCategory extends BaseTagCategory
{
/**
* @ORM\OneToMany(targetEntity="Tag", mappedBy="category", orphanRemoval=true)
*/
protected $tags;
}
標籤類:
class Tag extends BaseTag
{
/**
* @Assert\NotBlank()
* @ORM\ManyToOne(targetEntity="TagCategory", inversedBy="tags")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id", nullable=false)
*/
protected $category;
/**
* @var ArrayCollection List of products that have this tag assigned
*
* @ORM\ManyToMany(targetEntity="Product", mappedBy="tags")
*/
protected $products;
}
我需要做的是,對於給定的產品列表,獲取這些產品的標籤有,並且,爲每個標籤,獲得具有該標籤的產品數量。
我也想檢索由TagCategory分組的標籤,因爲它們需要呈現分組。
這裏是我試過的查詢之一,它是在TagCategory庫:
$qb->select('c as tagCategory, t as tag, COUNT(t) as total')
->from($this->_entityName, 'c')
->leftJoin('c.tags', 't')
->leftJoin('t.products', 'p')
->where(
$qb->expr()->in('p.id', $productsIds)
)
->groupBy('t.id')
;
這使我有以下結構的陣列:
array(3) {
[0]=> array(2) {
["tagCategory"]=> array(4) {
["id"]=>
["name"]=>
["slug"]=>
["tags"]=> array(2) {
[0]=> array(4) {
["id"]=>
["order"]=>
["name"]=>
["slug"]=>
}
[1]=> array(4) {
["id"]=>
["order"]=>
["name"]=>
["slug"]=>
}
}
}
["total"]=>
}
此查詢組中的所有標籤在一個類別中,這是我想要的,但它將總數設置爲最高級別,並將其作爲類別中最後一個標記的總數。我需要總數作爲標籤實體的另一個屬性。
我也試着這樣做查詢,在標籤庫:
$qb->select('c as tagCategory, t as tag, COUNT(t) as total')
->from($this->_entityName, 't')
->leftJoin('t.category', 'c')
->leftJoin('t.products', 'p')
->where(
$qb->expr()->in('p.id', $productsIds)
)
->groupBy('t.id')
;
該查詢給我的標籤陣列,與該類別總的財產,這是正確的,但我需要將標籤分組在一個類別內:
array(4) {
[0]=> array(2) {
["tag"]=> array(5) {
["id"]=>
["order"]=>
["name"]=>
["slug"]=>
["category"]=> array(3) {
["id"]=>
["name"]=>
["slug"]=>
}
}
["total"]=>
}
我需要類似這樣的東西,可以這樣做嗎?
array(3) {
[0]=> array(2) {
["tagCategory"]=> array(4) {
["id"]=>
["name"]=>
["slug"]=>
["tags"]=> array(2) {
[0]=> array(4) {
["id"]=>
["order"]=>
["name"]=>
["slug"]=>
**["total"]=>**
}
[1]=> array(4) {
["id"]=>
["order"]=>
["name"]=>
["slug"]=>
**["total"]=>**
}
}
}
}
謝謝。
產品中的主鍵列被稱爲「cod_pro」,這就是爲什麼我使用referencedColumnName – Joel
ohh我看我的意思是默認主鍵是在symfony中的ID所以... –
在這裏我已經完成了這種類型的代碼,它會幫助您$查詢= $這個 - > createQueryBuilder( 'S') - >選擇( 'S') - >連接( 'S.songsPlaylists', 'AP',EXPR \加入:: WITH「ap.id =:用戶 ') - >的setParameter(' 用戶」,$用戶) - > getQuery(); –