我使用多对多的关系;
用户实体;
/**
* @ORM\ManyToMany(targetEntity="Conversation", inversedBy="users")
*/
protected $conversations;
会话实体;
/**
* @ORM\ManyToMany(targetEntity="User", mappedBy="conversations")
* @ORM\JoinTable(name="user_conversation")
*/
protected $users;
何时,我正在使用此功能;
$user->getConversations();
Symfony在后台使用这个sql代码;
SELECT
t0.id AS id1,
t0.conversationid AS conversationid2
FROM
Conversation t0
INNER JOIN user_conversation ON t0.id = user_conversation.conversation_id
WHERE
user_conversation.user_id = ?
并选择所有对话。这将是性能问题。所以,我使用存储库类。但是,我不能一起做多对多和限制功能。我该怎么办?我写给存储库类的内容是什么?
答案 0 :(得分:5)
如果您想在学说中优化对大型馆藏的访问,请使用Criteria (That only works on OneToMany associations.)
实施例:
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Criteria;
/**
* @ORM\Entity
* @ORM\Table
*/
class User
{
....
public function getLatestConversation()
{
$criteria = Criteria::create()
->setMaxResults(10);
return $this->conversations->matching($criteria);
}
}
对于ManyToMany,我认为您必须创建自定义查询:
public function getLatestConversations($user)
{
$qb = $this->createQueryBuilder("c");
$qb
->leftjoin("c.users", "u")
->where("u = :user")
->setParameter("user", $user)
->setMaxResults(2);
return $qb->getQuery()->getResult();
}
答案 1 :(得分:1)
您可以将其转换为Arraycollection对象:
$input = $repo->getConversations(); //manytomany relation
$arr = new ArrayCollection();
foreach ($input as $e){
$arr->add($e);
}
然后在$ arr上使用你的Criteria
答案 2 :(得分:0)
尝试
$repository = $em->getRepository('YourBundle:Conversations');
$query = $repository->createQueryBuilder('C')
->join('C.Users', 'U')
->where('U.id = :uid')
->setMaxResults(20) //set your amount for limit
->setParameter('uid', $user_id)
->getQuery();
$result = $query->getResults();