[英]doctrine2 checking if one entity is related to other over ManyToMany relation
例如,我有2個實體: event
和user
都具有ManyToMany
關系。
class Event {
/**
* @Id @Column(type="integer") @GeneratedValue
*/
protected $id;
/**
* @ManyToMany(targetEntity="User", inversedBy="participated_events")
*/
protected $participations;
}
和
class User {
/**
* @Id @Column(type="integer") @GeneratedValue
* */
protected $id;
/**
* @ManyToMany(targetEntity="Event", inversedBy="participations")
*/
protected $participated_events;
}
我如何檢查$em->getRepository('event')->find(RANDOM_ID)
和$em->getRepository('user')->find(RANDOM_ID)
是否在參與方面彼此相關? 換句話說,如何檢查用戶是否參與了此事件? 什么是最好的方法? 我知道我可以參加所有參與的活動並檢查foreach()
但是我認為這必須是一種更簡單的方法。
謝謝。
您必須創建一個自定義存儲庫DQL,並選擇要執行的字段。
我個人而言,避免使用教義關系多對多關系,因為如果我在join_table中需要額外的列,那么對我來說,做事情就更容易。 因此,我幾乎總是用相應的manyTo和onetoMany引用創建一個連接實體。 因此,在您的實例中,將有一個ParticipatedEvent實體,該實體具有manyToOne用戶和manyToOne事件(並在其目標Entites oneToMany上)您仍然有關系,但是您有額外的加入模型(或實體)
因此,您最終會像這樣:
$particpated_event = $em->getRepository('ParticipatedEvents')->findOneBy('event_id'=>RANDOM_ID, 'user_id'=>RANDOM_USER_ID);
if($particpated_event) {
$event = $particpated_event->getEvent(); //or get user.
}
你可以像這樣做
$particpated_events = $em->getRepository('event')->find(RANDOM_ID)->getParticipatedEvents();
foreach( $particpated_events as $particpated_event){
$user = $particpated_event->getUser();
}
再次查看最適合您的。 如您所言,您可以使用DQL查詢創建存儲庫類
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.