php Doctrine2 findBy 关系对象触发字符串转换错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4619071/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 13:43:00  来源:igfitidea点击:

Doctrine2 findBy relationship object triggers string conversion error

phpdoctrine-orm

提问by pdd

Say I have two entities in Doctrine2 that are related to each other, Models\User and Models\Comment. If I do this in Doctrine 2.0.0...

假设我在 Doctrine2 中有两个相互关联的实体,Models\User 和 Models\Comment。如果我在 Doctrine 2.0.0 中这样做......

<?php
// $em instanceof EntityManager, $user instanceof Models\User
$comments = $em->getRepository('Models\Comment')
    ->findBy(array('user' => $user, 'public' => true));

...I get a PHP error:

...我收到一个 PHP 错误:

Severity: Notice

Message: Object of class Models\User to string conversion

Filename: DBAL/Connection.php

Line Number: 574

严重性:注意

消息:类 Models\User 到字符串转换的对象

文件名:DBAL/Connection.php

行号:574

This shouldn't happen, right? If I use the QueryBuilder and setParameter('user', $user) it works as expected.

这不应该发生,对吧?如果我使用 QueryBuilder 和 setParameter('user', $user) 它会按预期工作。

回答by beberlei

Query by relationship is allowed, but you have to pass the Identifier in there. Query by object is not yet supported and will only make it into 2.1.

允许按关系查询,但您必须在其中传递标识符。尚不支持按对象查询,只会将其纳入 2.1。

<?php
// $em instanceof EntityManager, $user instanceof Models\User
$comments = $em->getRepository('Models\Comment')
->findBy(array('user' => $user->getId(), 'public' => true));

回答by Cobby

Unfortunately, I don't think query by relationships is supported directly via repository objects.

不幸的是,我不认为通过存储库对象直接支持按关系查询。

In this case, you are probably best to write a custom repository class with a findByUser method.

在这种情况下,您可能最好使用 findByUser 方法编写自定义存储库类。

<?php

namespace App\Domain\Repository;

use Doctrine\ORM\EntityRepository,
    App\Domain\Entity\User;

class CommentRepository extends EntityRepository
{

    public function findByUser(User $user)
    {
        // add QueryBuilder code here
    }

}

Don't forget to update your Comment entity to use the custom repository:

不要忘记更新您的 Comment 实体以使用自定义存储库:

<?php

namespace App\Domain\Entity;


/** 
 * @Entity(repositoryClass="App\Domain\Repository\CommentRepository")
 */
class Comment 
{

    // entity definition

}

回答by vimuth

For symfony 4.1 this code worked for me.

对于 symfony 4.1,这段代码对我有用。

$comments = $this->getDoctrine()
                ->getRepository(Models\Comment::class)
                ->findBy(
                ['user' => $user->getId(), 'public' => true]
);