[Drupal] How to get organic groups membership entity ID in Drupal 7

| | 1 min read

There are situations where we need organic groups membership entity ID. Some of situations are : we use the function og_membership_delete() when we want to remove programmatically a user or node or any group content from our group, which will require parameter that is organic groups membership entity ID. Also when come across og_membership_load() function to get the entire organic groups membership object, which will also require OG membership entity ID as parameter. So in these situations how can we get organic groups membership object membership entity ID. See the following function I have written to retrieve the organic groups membership object membership entity Id.

  
    /**
     * Get OG membership entity ID.
     * 
     * @param int $gid.
     *   The Organic group ID.
     * @param int $etid.
     *   The entity ID of the group content.
     * @param string $entity_type.
     *   The entity type of the group content.
     * 
     * @return int.
     *   The OG membership entity ID.
     */
    function my_module_get_og_membership_entity_id($gid, $etid, $entity_type) {
      $result = db_query("SELECT og.id
        FROM {og_membership} og
        WHERE og.gid=:gid
        AND og.etid=:etid
        AND og.entity_type=:entity_type",
        array(
          ':gid' => $gid,
          ':etid' => $etid,
          ':entity_type' => $entity_type,
        )
      );
      $entity_exists = $result->rowCount();
      if ($entity_exists) {
        foreach ($result as $record) {
          return $record->id;
        }
      }
      return FALSE;
    }
  

The above function will return the OG membership entity ID, if there exists any og membership entity with the parameters passed, otherwise returns FALSE.