Symfony/Doctrine - Twig_Error_Runtime: Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string

Symfony/Doctrine - Twig_Error_Runtime: Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string

我的 symfony 项目中有这个实体:

/**
 * Batiments
 *
 * @ORM\Table(name="batiments")
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="MySpace\DatabaseBundle\Repository\BatimentsRepository")
 */
class Batiments
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

/**
     * @var string
     *
     * @ORM\Column(name="nom", type="string", length=150, nullable=true)
     */
    private $nom;

    /**
     * @ORM\ManyToOne(targetEntity="MySpace\DatabaseBundle\Entity\Ensembles")
     * @ORM\JoinColumn(nullable=false)
     */
    private $ensembles;

    /**
 * @ORM\ManyToMany(targetEntity="MySpace\DatabaseBundle\Entity\Typesactivite")
 * @ORM\JoinTable(name="batiments_typesactivite",
 *      joinColumns={@ORM\JoinColumn(name="batiments_id", referencedColumnName="id", nullable=false)},
 *      inverseJoinColumns={@ORM\JoinColumn(name="typesactivite_id", referencedColumnName="id", nullable=false)}
 *      )
 */
private $typesactivite;

//getters and setters

如您所见,我有 $ensembles 的关系 ManyToOne$typesactiviteManyToMany 关系。

我有这个 SQL 请求:

SELECT b.referenceBatiment, b.nom, e.nom, p.nom, b.surfaceChauffee, ta.type
FROM `batiments` b, `ensembles` e, `parcsimmobilier` p, `typesactivite` ta, `batiments_typesactivite` bta
WHERE b.ensembles_id = e.id
AND e.parcsimmobilier_id = p.id
AND b.id = bta.batiments_id
AND ta.id = bta.typesactivite_id
GROUP BY p.nom, e.nom, b.nom, ta.type

PhpMyAdmin 上,SQL 请求运行良好,所以我必须在我的 Symfony 项目(DQL with Doctrine)中导入我的 SQl 请求.

我在 controller.php:

中试试这个
$query=$em->createQuery('SELECT b
                         FROM MySpaceDatabaseBundle:Ensembles e,  MySpaceDatabaseBundle:Typesactivite ta, MySpaceDatabaseBundle:Parcsimmobilier p, MySpaceDatabaseBundle:Batiments b
                         WHERE b.ensembles = e.id
                         AND b.typesactivite = ta.id');

它似乎有效,但仅适用于 ManyToOne 关系。我在 html.twig 中的 <table> 标签中显示结果,如下所示:

<table id="dataTablesBatiments" class="table table-bordered table-hover" cellspacing="0" width="100%">
                <thead>
                  <tr>
                    <th>Référence</th>
                    <th>Parc</th>
                    <th>Nom</th>
                    <th>Ensemble</th>
                    <th>Type d'activité</th>
                    <th>Surface</th>
                    <th></th>
                  </tr>
                </thead>
                <tbody>
                  {% for batiments in batiment %}
                    <tr>
                      <td>{{ batiments.referencebatiment }}</td>
                      <td>{{ batiments.ensembles.parcsimmobilier }}</td>
                      <td>{{ batiments.nom }}</td>
                      <td>{{ batiments.ensembles }}</td>
                      <td>{{ batiments.typesactivite }}</td>
                      <td>{{ batiments.surfacechauffee }}</td>
                      <td><a href=""><button class="btn btn-warning btn-xs">Modifier</button></a></td>
                    </tr>
                  {% endfor %}
              </tbody>
            </table>

但是我有这个错误:

[Semantical Error] line 0, col 328 near 'typesactivite': Error: Invalid PathExpression. StateFieldPathExpression or SingleValuedAssociationField expected.


最后更新


根据学说参考文档和 Symfonybook 的所有建议,我尝试这样做。这是删除查询请求后我的控制器中的代码:

$em=$this->getDoctrine()->getManager();
        $batiment = $em->getRepository('MySpaceDatabaseBundle:Batiments')->findAll();

        return $this->render('MySpaceGestionPatrimoinesBundle:Batiments:indexBatiments.html.twig', array('batiment' => $batiment ));
}

但是现在出现这个错误:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class Doctrine\ORM\PersistentCollection could not be converted to string in C:\wamp\www.........\app\cache\dev\twig\bf6a31a62bf6f2a549d2604fb5be9c4530ab760a10169af08e8a5b72e9ee.php line 127") in MySpaceGestionPatrimoinesBundle:Batiments:indexBatiments.html.twig at line 60.

如你所见,在我的树枝上,一切都很好。有人吗?

感谢您的帮助。

也许 IDENTITY 可以帮助您... IDENTITY(b.typesactivite)

编辑

替代方案是这样的

假设 $qb 是您的查询生成器实例

$qb->select("b")->from("Batiments", "b")
   ->leftJoin("Ensemble", "e", \Doctrine\ORM\Query\Expr\Join::WITH, "b.ensembles = e.id")
   ->leftJoin("Typesactivite", "ta",  \Doctrine\ORM\Query\Expr\Join::WITH, "b.typesactivite = ta.id");

试试这个(@Gregsparrow 建议):

$qb = $this-> $em->getRepository("YourBundle:Batiments")
                        ->createQueryBuilder('b');

// @Gregsparrows suggestion queryBuilder
$qb ->select("b")
    ->from("Batiments", "b")
    ->leftJoin(...")
    ->leftJoin("...");

$batiment = $qb->getResult();

return $this->render('...') ;

匹配吗?

错误

$batiment = $em->getRepository('MySpaceDatabaseBundle:Batiments');
$qb = $this->$em->createQueryBuilder(b);

$qb = $em->getRepository('MySpaceDatabaseBundle:Batiments')->createQueryBuilder('b');

也许你应该尝试这样的事情:

$batiments = $this->createQueryBuilder('b')
->join('b.ensembles', 'e')
->join('b.typesactivites', 'ta')
->addSelect('e')
->addSelect('ta')
->where('b.ensembles = :ensembles')
->andWhere('b.typesactivite= :typesactivite');

请记住您使用的是 Doctrine,因此 枢轴 table batiments_typesactivite存在于你的symfony项目中,考虑OOP和对象关系


更新

这是否匹配:

   $batiments = $this->createQueryBuilder('b')
    ->join('b.ensembles', 'e')
    ->join('b.typesactivites', 'ta')
    ->addSelect('e')
    ->addSelect('ta')
    ->where('b.ensembles = :ensembles')
    ->andWhere('b.typesactivite= :typesactivite');

$batiment = $query->getResult();

根据http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#many-to-many-unidirectional and http://doctrine-orm.readthedocs.org/en/latest/reference/association-mapping.html#many-to-many-bidirectional,你的两个实体之间需要的不是一个整数值,而是一个整体table。 如果我正确理解你的模型,一个 "Batiment" 可以有多个 "Type d'activité",反之亦然,因此你需要一个 "BatimentTypeActivite" table 在中间。 结果 tables 看起来像这样:

基础设施 ID 名字

激活 ID 名字

BatimentActivite id_batiment id_activite

你应该试试这段代码,实际上 fetch join:

    $queryBatiments = $em->createQuery('SELECT b, ta, e
                                    FROM MySpaceDatabaseBundle:Batiments b
                                    JOIN b.typesactivite ta
                                    JOIN b.ensembles e
                                    WHERE b.ensembles = e.id');

    $batiment = $queryBatiments->getResult();

    return $this->render ('MySpaceGestionPatrimoinesBundle:Batiments:indexBatiments.html.twig', array ('batiment' => $batiment ));
}

根据 Doctine 参考文档 here 中的 join 参数,也许您必须使用 DQL 请求获取连接。

符合你的问题吗?

看来我找到了解决方案,多亏了另一位开发者(顺便再次感谢你)。

看看:事实上你必须在你的树枝上做一个环。

因为在你的代码中应该是这样的:

<tbody>
       {% for batiments in batiment %}
         <tr>
           <td>{{ batiments.referencebatiment }}</td>
           <td>{{ ... }}</td>
           <!-- your loop here -->
           <td>
             {% for batiments in batiments.typesactivite %}
               {{ batiments.type }}
             {% endfor %}
           </td>
        {% endfor %}
</tbody>

希望对你有帮助。