How to filter a dataset with a multi reference

Hi,

I have a dataset (dataset1) with a reference record. In this record you can select multiple values from an other dataset (dataset2).

dataset1

dataset2

Question : How can I filter this dataset with code?

I tried:

$w('#dataset1').setFilter(wixData.filter().hasSome("eventTyp","2"));

Result have to be : Event 1 and Event 2

Reference fields within wix store the data ID as the main Value, This would be the referenced data’s _id field. So a hasSome record needs to be used to search that Items ID, Not a field contained within the ID.

Data = Reference field in database 1 has 3 items with ID’s (ID1, ID2, ID3) to search this you would utilise

$w('#dataset1').setFilter(wixData.filter().hasSome("eventTyp",["ID1", "ID3"])) 

This would return items 1 and 3 of the database.


If it is a Text field rather than a reference field then put the items within an array still

Data = Text field in database 1 has 3 items with Strings (Blue, blue, Red, Black, Purple) to search this you would utilise

$w('#dataset1').setFilter(wixData.filter().hasSome("eventTyp",["Blue", "Black"]))

This would return items 1 and 4 only,
Note: This will not return item 2 as the Has Some filter is case sensitive.


On another note if you only want to check a text field for a single string without case sensitivity utilise

IE Text field in database 1 has 3 items with Strings (Blue, blue, Red, Black, Purple) to search this you would utilise

$w('#dataset1').setFilter(wixData.filter().contains("eventTyp","blue"))

This would return items 1 & 2 as the query is a single string with contains and is not case sensitive.

Following on from Scott’s excellent reply above, you can also read Wix pages about reference fields if you have not already done so.
https://support.wix.com/en/article/about-reference-fields-in-database-collections
https://support.wix.com/en/article/referencing-multiple-items-in-one-database-field
https://support.wix.com/en/article/working-with-multiple-item-reference-fields

Thank you guys :slight_smile:

No worries at all if your happy with the response please mark as best answer so someone else can easily find it in the future if needed :slight_smile:

Hi Everyone, got the above to work, i was wondering how I can filter 2 reference fields, these are my codes:

$w.onReady(() => {
$w( “#collectionsDataset” ).onReady(() => {
let itemObj = $w( ‘#collectionsDataset’ ).getCurrentItem();
collection = itemObj._id;
});
});

// ------------------------------------------------------------------- Product Filters ------------------------------------------------- //
export function filter_change(event) {
$w( ‘#noresults’ ).collapse();
$w( ‘#anchor’ ).scrollTo();
$w( ‘#loading’ ).expand();
$w( ‘#productRepeater’ ).collapse();
$w( ‘#load’ ).collapse();

if ($w( ‘#filter’ ).value === ‘All’ ) {

    $w( '#productsDataset' ).setFilter(wixData.filter().hasSome( "collection" ,collection)) 

        .then(() => { 

let count = $w( “#productsDataset” ).getTotalCount();
console.log( “Products are already filtered” );

            setTimeout( **function**  () { 
                $w( '#loading' ).collapse(); 
                $w( '#productRepeater' ).expand(); 
                $w( '#load' ).expand(); 
                $w( '#sort' ).enable(); 
                console.log( "Result" ); 

            },  1500 ); 
            $w( "#count" ).text =  'Showing '  + String(count) +  ' items from this category.' ; 
        }) 
}  **else**  { 

    $w( '#productsDataset' ).setFilter(wixData.filter().hasSome( "collection" ,collection) 
    .hasSome( "productType" ,$w( '#filter' ).value)) 
        .then(() => { 

let count = $w( “#productsDataset” ).getTotalCount();
console.log( “Products are already filtered” );
if (count > 0 ) {

                setTimeout( **function**  () { 
                    $w( '#loading' ).collapse(); 
                    $w( '#productRepeater' ).expand(); 
                    $w( '#load' ).expand(); 
                    $w( '#sort' ).enable(); 
                    console.log( "Result" ); 
                },  1500 ); 

            }  **else**  { 

                setTimeout( **function**  () { 
                    $w( "#loading" ).collapse(); 
                    $w( '#productRepeater' ).collapse(); 
                    $w( '#load' ).collapse(); 
                    $w( '#noresults' ).expand(); 
                    $w( '#sort' ).disable(); 
                    console.log( "No result" ); 
                },  1500 ); 
            } 
            $w( "#count" ).text =  'Showing '  + String(count) +  ' items from this category.' ; 
        }) 

        . **catch** ((err) => { 
            console.log(err); 
        }); 

} 

}

I tried that one, but it wouldn’t filter by the value of the text element I’d created that was separate from the repeaters. Basically, I clicked on the genre collection to change the value of that text element, and that text value was then used to filter the second database through the multiref field that connected both collections. It wouldn’t filter it. I tried “.filter”, “.setFilter”, “hasSome”, “.include”, and even “.contains” in multiple different ways.

Once I finally figured out the queryReferenced() code, I managed to add that to query() and connect the filter through that. That finally worked so that the console log shows the filtered data correctly as arrays and json data. Now I’m trying to connect that data to my repeater via code (lol, I kinda forgot how to do that). Here’s what I have so far, which works perfectly (except for connecting the data to the repeater):

import wixData from ‘wix-data’;

$w.onReady(function () {
const gRepeater = $w(“#gRepeater”);
const GenreTextHeader = $w(“#GenreTextHeader”);
gRepeater.onItemReady(($item, itemData, index) => {
// Get the genre pic and corresponding gText element
const GenrePic = $item(“#GenrePic”);
const gText = $item(“#gText”);
GenrePic.onClick(() => {
GenreTextHeader.text = gText.text;
let sFilter = $w(‘#GenreTextHeader’).text;
console.log(sFilter);
});
});
});

$w(“#GenrePic”).onClick(() => {
const genre = $w(“#GenreTextHeader”).text; // Get the text value from your GenreTextHeader element

// Query the second database to find rows that match the genre
wixData.query("7bfg") // name of your second database collection
    .eq("g", genre)
    .find()
    .then((secondDatabaseResults) => {
        // Extract the row IDs of matching rows
        const matchingRowIds = secondDatabaseResults.items.map(item => item._id);

        // Query the first database and filter based on the matching row IDs from the second database
        wixData.query("7bfst") // Replace "FirstDatabaseCollection" with the actual name of your first database collection
            .hasSome("7bfg_mr", matchingRowIds)
            .find()
            .then((firstDatabaseResults) => {
                console.log("Filtered results from the first database:", firstDatabaseResults.items);
            })
            .catch((error) => {
                console.error("Error querying the first database:", error);
            });
    })
    .catch((error) => {
        console.error("Error querying the second database:", error);
    });

});