Wally Kolcz
Wally Kolcz

Reputation: 1664

Querying Pods.io for related records

This is going to drive me absolutely crazy. I have custom content types using Pods and I am trying to get all related records based on a parent. In this case I have states and counties.

I start with:

$states = pods( 'state', $params);

And sure enough I get all the states entered. Next I want to loop through all the states and get the counties that are related to the state by the 'state_id' but have no idea on how to do that. Here is what I have.

while ( $states->fetch() ) {
    echo $states->display( 'state_name' ) . "<br />";
    $params = [
        'where'=>"meta_value.state_id = 19"
    ];
    $county = pods( 'county', $params);
    print_r($county);
}

Of course the where clause is wrong but the documentation is confusing at best. I see things like 'related_field_name.meta_value' or 'related_field_name.field_name'. I tried the above query with the where clause having state.meta_value=19 (the state ID that is related to the county) and it just given me a huge list of information but no records.

In the wordpress database I have the wp_postmeta which contains a number of meta_key and meta_value for the county record including one meta_key of 'state_id' with the value of '19' which I want to match up in the loop.

How can I say 'Grab me all the post records that have an state_id of 19'?

Upvotes: 0

Views: 1518

Answers (1)

Scott Kingsley Clark
Scott Kingsley Clark

Reputation: 987

Try this:

<?php
$params = array(
    'limit' => -1,
);

$states = pods( 'state', $params );

while ( $states->fetch() ) {
    // Pods::index() maps to "post_title"
    echo '<h3>' . $states->index() . '</h3>';

    // Pods::id() maps to "ID"
    $county_params = array(
        'where' => 'state_id.meta_value = ' . (int) $states->id(),
    );

    /*
    // If you had a relationship field instead
    // and the field was named "state"
    // and it was related to the "state" post type
    // then it would be:
    $county_params = array(
        'where' => 'state.ID = ' . (int) $states->id(),
    );
    */

    $county = pods( 'county', $county_params );

    // List all counties for state
    if ( 0 < $county->total() ) {
        echo '<ul>';

        while ( $county->fetch() ) {
            // index() maps to "post_title"
            echo '<li>' . $county->index() . '</li>';
        }

        echo '</ul>';
    }
}

Upvotes: 0

Related Questions