假设我有两个实体User和Product与Doctrine的多对多关系相关.
我想知道为我的User实体处理$ user-> hasProduct($ product)方法的最佳方法,即返回true是关系存在,否则返回false.
我现在正在这样做:
public function hasProduct($id)
{
foreach($this->getProducts() as $product) {
if($product->getId() == $id) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
但我不确定这是最好的方式,特别是如果循环中有很多关系.
如果有人有更好的东西,请告诉我:)
Pie*_*ouw 54
你的功能getProducts给你一个ArrayCollection.
做就是了
if($user->getProducts()->contains($product)) //the real product object not the id
//your stuff
Run Code Online (Sandbox Code Playgroud)
编辑:
对于树枝模板:
{% if product in user.products %}
//your stuff
{% endif %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9148 次 |
| 最近记录: |