Related Entries Backwards


/ Published in: PHP
Save to your folder(s)



Copy this code and paste it in your HTML
  1. global $DB;
  2.  
  3. $this_entry_id = "{entry_id}";
  4. $related_field = "member_related_org";
  5.  
  6. // Query for field id of related field
  7. $rel_field_id_query = $DB->query("SELECT field_id FROM exp_weblog_fields WHERE field_name = '$related_field'");
  8. $field_id = 'field_id_'.$rel_field_id_query->row['field_id'];
  9.  
  10. // Query for rel_id values in the exp_relationships table
  11. $rel_id_query = $DB->query("SELECT rel_id FROM exp_relationships WHERE rel_child_id = '$this_entry_id'");
  12.  
  13. if($rel_id_query->num_rows > 0)
  14. {
  15. // Build query to grab all related entries based off of the rel_id values
  16. $rel_query_chunk = '(';
  17.  
  18. foreach($rel_id_query->result as $row)
  19. {
  20. $rel_id = $row['rel_id'];
  21.  
  22. $rel_query_chunk .= "OR exp_weblog_data.${field_id} = '$rel_id' ";
  23. }
  24.  
  25. $rel_query_chunk .= ')';
  26.  
  27. $find = array(
  28. '(OR ',
  29. ' )'
  30. );
  31.  
  32. $replace = array(
  33. '(',
  34. ')'
  35. );
  36.  
  37. $rel_query_chunk = str_replace($find, $replace, $rel_query_chunk);
  38.  
  39. $sql = "
  40. SELECT * FROM exp_weblog_titles
  41. LEFT JOIN exp_weblog_data ON exp_weblog_data.entry_id = exp_weblog_titles.entry_id
  42. WHERE $rel_query_chunk
  43. ";
  44.  
  45. // Query for entry data
  46. $rel_entry_query = $DB->query($sql);
  47.  
  48. if($rel_entry_query->num_rows > 0)
  49. {
  50. foreach($rel_entry_query->result as $row)
  51. {
  52. $entry_id = $row['entry_id'];
  53. $title = $row['title'];
  54. }
  55. }
  56. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.