From 347eefa7e2399e101e367e58571cca0ccc526fbb Mon Sep 17 00:00:00 2001 From: weryques Date: Tue, 29 May 2018 14:45:16 -0300 Subject: [PATCH] Adds fetch all values of a field from a repository --- .../repositories/class-tainacan-fields.php | 56 +++++++++++++++---- 1 file changed, 44 insertions(+), 12 deletions(-) diff --git a/src/classes/repositories/class-tainacan-fields.php b/src/classes/repositories/class-tainacan-fields.php index 7927d6983..0618eacaa 100644 --- a/src/classes/repositories/class-tainacan-fields.php +++ b/src/classes/repositories/class-tainacan-fields.php @@ -642,11 +642,8 @@ class Fields extends Repository { } } - - # TODO: Fetch all field value for repository level - /** - * Fetch all values of a field from a collection in all it collection items + * Fetch all values of a field from a collection or repository * * @param $collection_id * @param $field_id @@ -725,8 +722,9 @@ class Fields extends Repository { foreach ($post_statuses as $post_status) { - $sql_string = $wpdb->prepare( - "SELECT item_id, field_id, mvalue + if($collection_id) { + $sql_string = $wpdb->prepare( + "SELECT item_id, field_id, mvalue FROM ( SELECT ID as item_id FROM $wpdb->posts @@ -737,8 +735,24 @@ class Fields extends Repository { FROM $wpdb->postmeta $search_query ) metas ON items.item_id = metas.post_id AND metas.field_id = %d", - $item_post_type, $post_status, $field_id - ); + $item_post_type, $post_status, $field_id + ); + } else { + $sql_string = $wpdb->prepare( + "SELECT item_id, field_id, mvalue + FROM ( + SELECT ID as item_id + FROM $wpdb->posts + WHERE post_status = %s + ) items + JOIN ( + SELECT meta_key as field_id, meta_value as mvalue, post_id + FROM $wpdb->postmeta $search_query + ) metas + ON items.item_id = metas.post_id AND metas.field_id = %d", + $post_status, $field_id + ); + } $pre_result = $wpdb->get_results( $sql_string, ARRAY_A ); if (!empty($pre_result)) { @@ -753,8 +767,10 @@ class Fields extends Repository { $post_statuses = get_post_stati( $args, 'names', 'and' ); foreach ($post_statuses as $post_status) { - $sql_string = $wpdb->prepare( - "SELECT item_id, field_id, mvalue + + if($collection_id) { + $sql_string = $wpdb->prepare( + "SELECT item_id, field_id, mvalue FROM ( SELECT ID as item_id FROM $wpdb->posts @@ -765,8 +781,24 @@ class Fields extends Repository { FROM $wpdb->postmeta $search_query ) metas ON items.item_id = metas.post_id AND metas.field_id = %d", - $item_post_type, $post_status, $field_id - ); + $item_post_type, $post_status, $field_id + ); + } else { + $sql_string = $wpdb->prepare( + "SELECT item_id, field_id, mvalue + FROM ( + SELECT ID as item_id + FROM $wpdb->posts + WHERE post_status = %s + ) items + JOIN ( + SELECT meta_key as field_id, meta_value as mvalue, post_id + FROM $wpdb->postmeta $search_query + ) metas + ON items.item_id = metas.post_id AND metas.field_id = %d", + $post_status, $field_id + ); + } $pre_result = $wpdb->get_results( $sql_string, ARRAY_A );