Create an index of the metadata type options to enable searches #251

This commit is contained in:
Leo Germani 2019-07-30 18:04:26 -03:00
parent 689c0d5819
commit 9b95b346ff
2 changed files with 85 additions and 0 deletions

View File

@ -535,6 +535,7 @@ class Metadata extends Repository {
$new_metadatum = parent::insert( $metadatum );
$this->update_taxonomy_metadatum( $new_metadatum );
$this->update_metadata_type_index( $new_metadatum );
return $new_metadatum;
}
@ -1352,6 +1353,34 @@ class Metadata extends Repository {
}
}
/**
* Creates an index with the exploded values of metadata_type_options array. Each option is prefixed with '_option_'
* This is useful to allow metadata to be queried based on a specific value of a metadata type option.
* For example, fetch all taxonomy metadata which the taxonomy_id metadata type option is equal to 4
*
* $metadata_repository->fetch([
* 'meta_query' => [
* [
* 'key' => '_option_taxonomy_id',
* 'value' => 4
* ]
* ]
* ])
*
* @var Entities\Metadatum $metadatum
*/
private function update_metadata_type_index( Entities\Metadatum $metadatum ) {
$options = $this->get_mapped_property($metadatum, 'metadata_type_options');
if (!is_array($options)) {
return;
}
foreach ($options as $option => $value) {
update_post_meta($metadatum->get_id(), '_option_' . $option, $value);
}
}
/**
* @inheritDoc
*/

View File

@ -368,6 +368,62 @@ class Metadata extends TAINACAN_UnitTestCase {
$this->assertFalse($invalidMetadatum->validate());
}
function test_metadata_type_option_index() {
$Tainacan_Metadata = \Tainacan\Repositories\Metadata::get_instance();
$collection = $this->tainacan_entity_factory->create_entity(
'collection',
array(
'name' => 'test',
),
true
);
$tax = $this->tainacan_entity_factory->create_entity(
'taxonomy',
array(
'name' => 'tax_test',
'collections' => [$collection],
'status' => 'publish'
),
true
);
$metadatum = $this->tainacan_entity_factory->create_entity(
'metadatum',
array(
'name' => 'meta',
'description' => 'description',
'collection' => $collection,
'metadata_type' => 'Tainacan\Metadata_Types\Taxonomy',
'status' => 'publish',
'metadata_type_options' => [
'taxonomy_id' => $tax->get_id(),
'allow_new_terms' => 'no'
]
),
true
);
$test_meta = get_post_meta($metadatum->get_id(), '_option_taxonomy_id', true);
$this->assertEquals( $tax->get_id(), $test_meta );
$fetch = $Tainacan_Metadata->fetch([
'meta_query' => [
[
'key' => '_option_taxonomy_id',
'value' => $tax->get_id()
]
]
], 'OBJECT');
$this->assertEquals(1, count($fetch));
$this->assertEquals($metadatum->get_id(), $fetch[0]->get_id());
}
}