我在两个实体之间有多对多的双向:
/**
* Position
*
* @ORM\Table(name="applypie_position")
* @ORM\Entity(repositoryClass="Applypie\Bundle\PositionBundle\Entity\PositionRepository")
*/
class Position
{
const IS_ACTIVE = true;
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="Applypie\Bundle\UserBundle\Entity\Applicant", mappedBy="bookmarks")
*/
private $bookmarkedApplicants;
/**
* Applicant
*
* @ORM\Table(name="applypie_applicant")
* @ORM\Entity
*/
class Applicant
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="Applypie\Bundle\PositionBundle\Entity\Position", inversedBy="bookmarkedApplicants")
* @ORM\JoinTable(name="applypie_user_job_bookmarks",
* joinColumns={@ORM\JoinColumn(name="applicant_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="position_id", referencedColumnName="id")}
* )
*/
private $bookmarks;
我的问题是:在一个通过ID轻松显示位置的PositionControllers Action中,我需要知道当前申请人是否想要查看该位置是否有当前位置的书签。
我首先想到的是使用$ applicant-> getBookmarks()获取所有书签,然后在一个forearch中运行,检查当前位置的所有申请人书签,但我认为必须有一个更简单的方法?
谢谢
答案 0 :(得分:1)
如果你想保持面向对象,你可以这样做:
class Applicant
{
// fields and ORM annotations
public function hasBookmark(Bookmark $bookmark) {
return $this->bookmarks->contains($bookmark);
}
class MyController
{
public function testAction() {
$applicant = $this->getUser(); // or however you fetch the applicant object
$bookmark = $bookmarkRepository->find($bookmarkId); // again, however you get the bookmark object
// @var boolean $applicantHasBookmark
$applicantHasBookmark = $applicant->hasBookmark($bookmark);
// other controller code
}