问题描述
所以我在这个实体中定义了这个关系:
So I've this relations defined in my entities:
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
已经存在,不尝试再次插入,我正在做如下:
And I'm trying to check if a given pair producto_id
-norma_id
already exists for not try to insert it once again and I'm doing as follow:
$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();
}
}
但是我收到这个错误:
在Google上进行研究,在这里我发现可能这是一个错误点或者也许不是我们(我和报告问题的其他人)正在做错事。我找不到问题或问题在哪里,所以任何建议或帮助对我和他人来说都是好的。我唯一的想法是在RDBMS创建一个视图,然后创建一个读取它的实体,并检查记录是否已经存在,我没有其他任何想法?帮帮我?工作示例代码?
Doing a research on Google and here on SO I found that possible it's a bug as point here or perhaps is not and we (me and the others who report the issue) are doing something wrong. I can't find where the issue or problem is so any advice or help will be fine for me and others. The only idea I have in mind is create a view at RDBMS and then create a entity for read it and check if record already exists, I have not other than this one, any ideas? Help? Working example code?
推荐答案
实际上,您可以使用'database_connection'服务来检查是否存在这样的行:
Actually you can use 'database_connection' service to check if such row exists:
$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));
这比使用多对多关系方法来处理这个要容易得多。我会这样做,如果我不得不做你需要的(实际上我这样做)。
That's really easier than trying to handle this with many to many relations methods. I would do that if I had to do what you need (and actually I'm doing so).
这篇关于使用ManyToMany中的findBy检查UNIQUE行是否存在任何解决方法或工作解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!