cal*_*die 11 php orm doctrine doctrine-orm
我似乎无法在Doctrine文档中找到有关如何检查实体是否与另一个实体存在关系的任何提及:
http://www.doctrine-project.org/docs/orm/2.0/en/reference/working-with-associations.html
在Doctrine 1.x中,有一个exists被调用的方法可以在实体上调用来检查:
在Doctrine 2.0中,这是我倾向于做的事情.其他人使用什么技术?
<?php
class Group {
private $id;
protected $name;
protected $users;
public function __construct()
{
$this->colorgroups = new ArrayCollection();
}
public function hasUsers() {
return count($this->users) > 0;
}
}
Run Code Online (Sandbox Code Playgroud)
好吧 - 我今天偶然发现了正确的答案,同时查看了ArrayCollection类.您应该使用'isEmpty'方法.
从代码(评论是他们的,而不是我的)
/**
* Checks whether the collection is empty.
*
* Note: This is preferrable over count() == 0.
*
* @return boolean TRUE if the collection is empty, FALSE otherwise.
*/
public function isEmpty()
{
return ! $this->_elements;
}
Run Code Online (Sandbox Code Playgroud)
从我的例子来看
public function hasUsers() {
return !$this->users->isEmpty();
}
Run Code Online (Sandbox Code Playgroud)
Doctrine2使用与Doctrine1.2不同的架构.如果要检查某个组是否有某个与之关联的用户,您应该编写一个方法hasUser(User $user)来确定它:
public function hasUser(User $user) {
foreach ($this->users as $u) {
if ($u->equals($user)) {
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
如果要检查数据库中是否保持关系,则必须执行以下DQL查询:
SELECT 1 FROM MyProject\Entity\Group g WHERE :user MEMBER OF g.users;
Run Code Online (Sandbox Code Playgroud)
哪里:user是User对象.
你可以使用Exists方法http://www.doctrine-project.org/api/common/2.4/class-Doctrine.Common.Collections.ArrayCollection.html#_exists这样的东西
$someId = 123;
$p = function($key, $element) use ($someId){
return $element->getId() == $someId;
};
$u->exists($p); //here is your result
Run Code Online (Sandbox Code Playgroud)