Benas Radzevicius
Benas Radzevicius

Reputation: 377

doctrine2 checking if one entity is related to other over ManyToMany relation

For example I have 2 entities: event and user both has ManyToMany relation.

class Event {

/**
 * @Id @Column(type="integer") @GeneratedValue
 */
protected $id;
/**
 * @ManyToMany(targetEntity="User", inversedBy="participated_events")
 */
protected $participations;
}

and

class User {

/**
 * @Id @Column(type="integer") @GeneratedValue
 * */
protected $id;
/**
 * @ManyToMany(targetEntity="Event", inversedBy="participations")
 */
protected $participated_events;
}

how can i check if $em->getRepository('event')->find(RANDOM_ID) and $em->getRepository('user')->find(RANDOM_ID) is related to each other over participation? In other words how to check if user is participated in this event? What is the best way? I know that i could get all participated events and check over foreach() but i think that it must be an easier way.

Thanks.

Upvotes: 0

Views: 276

Answers (1)

Elijan
Elijan

Reputation: 1416

You have to create a custom repository DQL and do select fields you want to do.;

I, personally, avoid Doctrines many to many relations as it is easier for me to do things you want to do, aslo if i need extra columns in join_table. So, I almost always create a join Entity with corresponding manyTo one and onetoMany references. So in your instance there would be a ParticipatedEvent entity which has manyToOne users and manyToOne Events (and on their target Entites oneToMany) You stil have your relationship but you have extra join Model (or Entity)

So, you end up like this:

   $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.
   }

and you can stil do things like this

$particpated_events = $em->getRepository('event')->find(RANDOM_ID)->getParticipatedEvents();
foreach( $particpated_events as  $particpated_event){

      $user = $particpated_event->getUser();
  }

Again see what best suits fro you. You can, as said, create Repository class with DQL query

Upvotes: 1

Related Questions