Search code examples
wordpressmany-to-manypodscms

How to query all related items in a many to many relationship using Pods API?


I have two Pods:

  • course
  • participant

The pod course has a PICK field to the pod participant. The field is a multiple relationship field. So, each course item has multiple participants.

I want to find all the course items where a certain participant is related.

So, I guess a SQL query such as the following would do what I want:

SELECT DISTINCT `t`.* FROM `wp_pods_course` AS `t` WHERE t.id IN 
   (SELECT DISTINCT r.item_id FROM wp_podsrel AS r WHERE r.related_item_id = '42')

42 is the id of a participant.

I am trying to figure out how to write such a SQL query using Pods API:

$pod = pods('course');
$participant_id = $participant->field('id');
$params['where'] = "t.id in (SELECT r.id FROM ??? WHERE ???)";
$pod->find($params);

Is this the correct way to write such a query?


Solution

  • You're overcomplicating things, Pods does all of the joins for you automatically with one of it's most powerful features, field traversal.

    Try this:

    $pod = pods( 'course' );
    
    // I use ->id() because it's always the right ID field, no matter what pod type
    $participant_id = $participant->id();
    
    $params = array(
        'where' => 'participants.id = ' . (int) $participant_id
    );
    
    $pod->find( $params );
    

    Where particpants is your relationship field name, id is the field id on that related object.