【发布时间】:2016-07-14 23:57:53
【问题描述】:
我有 2 个实体 - Authors 和 Books,1 个作者可能有很多书。我想在表格中显示每个作者有多少本书(每个作者的数量不同)。我已经看到this 问题,还有this 和this 并尝试了这个,因为我认为这会是更优雅的解决方案:
<td>{{books|length}}</td>
但每次我得到所有作者的书籍总数。在我的控制器中,我得到这样的书:
$query = $em->createQuery('SELECT b FROM AB\ProjectBundle\Entity\Books u WHERE b.authorid in (:authorids)');
$query->setParameter('authorid',$authorids);
$books = $query->getResult();
作者是这样选择的:
$query = $em->createQuery('SELECT a FROM AB\ProjectBundle\Entity\Authors a');
$authorids = $query->getResult();
编辑:我的树枝循环
<tbody>
{% for authors in author %}
<tr>
<td>{{ authors.name }}</td>
<td>{{ authors.isactive }}</td>
<td>{{ books.authorid|length}}</td>
</tr>
{% endfor %}
</tbody>
EDIT 2 我的作者实体
class Author
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $name;
/**
* Set name
*
* @param string $name
* @return string
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
}
EDIT 3 Books 实体
<?php
namespace AB\ProjectBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
*
*/
class Books
{
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var \AB\ProjectBundle\Entity\Author
*/
private $authorid;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set Authorid
*
* @param \AB\ProjectBundle\Entity\Author $authorid
* @return Author
*/
public function setAuthorid(\AB\ProjectBundle\Entity\Author $authorid = null)
{
$this->authorid = $authorid;
return $this;
}
/**
* Get Authorid
*
* @return \AB\ProjectBundle\Entity\Author
*/
public function getAuthorid()
{
return $this->authorid;
}
/**
* Set name
*
* @param string $name
* @return string
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
}
没有注释,实体映射在 *.orm.yml 文件中。 Book.orm.yml:
AB\ProjectBundle\Entity\Books:
type: entity
table: Books
id:
id:
type: integer
nullable: false
unsigned: false
id: true
generator:
strategy: IDENTITY
fields:
name:
type: text
nullable: false
manyToOne:
authorid:
targetEntity: Author
cascade: { }
mappedBy: null
inversedBy: null
joinColumns:
authorid:
referencedColumnName: id
orphanRemoval: false
lifecycleCallbacks: { }
作者.orm.yml
AB\ProjectBundle\Entity\Author:
type: entity
table: Author
id:
id:
type: integer
nullable: false
unsigned: false
id: true
generator:
strategy: IDENTITY
fields:
name:
type: text
nullable: false
lifecycleCallbacks: { }
【问题讨论】:
-
Author 和 Book 实体有实际关系吗?如果是这样,您可以这样做
{{ author.books|length }}(其中“books”是您在 Author 实体中命名的 Book 关系) -
是的,有一个实际的关系,但我仍然继续获得所有书籍的总数。我只是不能告诉它分别显示与每个作者相关的书籍数量((
-
你能在输出作者/书籍信息的地方添加树枝循环吗?
-
当我得到书籍的总数并尝试使用它的一些属性(比如 authorid)时,我得到一个错误“Key 'authorid' for array with keys 0,1,2,3,我的树枝模板中不存在 4 等"
-
向我们展示您的作者实体