使用ManyToMany中的findBy,任何变通方法或工作解决方案检查UNIQUE行是否已存在?

时间:2014-11-17 15:08:01

标签: php symfony doctrine-orm doctrine many-to-many

所以我在我的实体中定义了这种关系:

class Producto
{
    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Norma", inversedBy="normasProducto", cascade={"persist"})
     * @ORM\JoinTable(name="nomencladores.norma_producto", schema="nomencladores",
     *      joinColumns={@ORM\JoinColumn(name="producto_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="norma_id", referencedColumnName="id")}
     * )
     */
    protected $productoNormas;

} 


class Norma
{
    /**
     * @ORM\ManyToMany(targetEntity="AppBundle\Entity\Producto", mappedBy="productoNormas", cascade={"persist"})
     */
    protected $normasProducto;
}

我正在尝试检查一对特定的producto_id - norma_id是否已经存在,因为我没有尝试再次插入它,而是按照以下方式执行:

$exists = $em->getRepository('AppBundle:Producto')->findOneByProductoNormas($productoId);

if ($exists) {
    $status = 400;
} else {
    try {
        $producto->addProductoNormas($normaEntity);
        $em->flush();
        $response['success'] = true;
    } catch (Exception $ex) {
        $status = 400;
        $response['error'] = $ex->getMessage();
    }
}

但是我收到了这个错误:

  

注意:未定义的索引:joinColumns in   /var/www/html/project.dev/vendor/doctrine/orm/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php   第1665行

在Google上进行研究,在此我发现它可能是一个错误点here或者可能不是,我们(我和其他报告此问题的人)做错了。我无法找到问题或问题所在,所以任何建议或帮助对我和其他人都没问题。我想到的唯一想法是在RDBMS上创建一个视图,然后创建一个实体来读取它并检查记录是否已经存在,除了这个,我还有什么想法?救命?工作示例代码?

2 个答案:

答案 0 :(得分:0)

我不知道明确的答案,但我遇到了同样的问题,而且它与我的实体注释有关,虽然不能告诉你究竟是什么......

这是一个包含照片和相册的工作示例

class Photo
    {
         /**
         * @ORM\ManyToMany(targetEntity="Acme\MyBundle\Entity\Album", inversedBy="photos")
         * @ORM\JoinColumn(nullable=true)
        */
        private $albums;

class Album
    {
        /**
         * @ORM\ManyToMany(targetEntity="Acme\MyBundle\Entity\Photo", mappedBy="albums")
         * @ORM\JoinColumn(nullable=true)
        */
        private $photos;

为了检查你可以做的存在,假设你正在搜索idPic照片

$photo = $repository ... ->findOneBy($idPic)
if($photo->getAlbums()->contains($album))

答案 1 :(得分:0)

实际上你可以使用' database_connection'服务以检查是否存在这样的行:

$this->get('database_connection')
     ->fetchColumn('select count(id) as cnt 
                    from <norma_producto_table> 
                    where producto_id = ? and 
                          norma_id = ?', array($producto_id, $norma_id));

这比尝试使用多对多关系方法处理它更容易。如果我必须做你需要的事情(我实际上是这样做的话),我会这样做。