2013-01-24 81 views
21

假设我有两个实体用户和产品通过与Doctrine的多对多关系相关。正确的方法来检查是否存在多对多关系 - Symfony2/Doctrine

我想知道为我的用户实体处理$ user-> hasProduct($ product)方法返回true的最佳方式是关系存在或否则返回false。

目前,我正在做这个:

public function hasProduct($id) 
{ 
    foreach($this->getProducts() as $product) { 
     if($product->getId() == $id) { 
      return true; 
     } 
    } 

    return false; 
} 

但我不知道这是最好的方式,特别是如果在环路许多关系。

如果有人有更好的东西,让我知道:)

回答

49

你的功能getProducts给你一个ArrayCollection

只是做

if($user->getProducts()->contains($product)) //the real product object not the id 
     //your stuff 

编辑:

对于树枝模板:

{% if product in user.products %} 
    //your stuff 
{% endif %} 
+0

听起来不错!我会用它。有没有办法在树枝模板中执行此操作? –

+0

如果我想检查如果具有给定名称的产品退出? – Abdel5

+0

您必须手动循环访问产品或使用自定义的“DQL”查询 – Pierrickouw

0

我用同样的问题所困扰,通过它完成解决了这个问题this博客条目来了通过使用Doctrine Filters。

如果我正确理解你的问题,你有三个表(用户,user_product和产品),你应该能够重写hasProduct($ id)的功能是这样的:

use Doctrine\Common\Collections\Criteria; 

public function hasProduct(int $productId): bool { 

    $criteria = Criteria::create(); 
    $criteria->where(Criteria::expr()->eq('id', $productId)); 

    if(count($this->products->matching($criteria)) > 0) { 
    return true; 
    } 

    return false; 
} 

运行此代码, Doctrine不加载链接到用户的所有产品。它实际上只查询交叉引用表(user_product)。

相关问题