laravel eloquent - check if all values of array in table

Viewed 1819

I have a table options and I have an array of strings ["value1", "value2", "value3"].

What I'd like to do is check if all of the values within the array are present in the table.

I've tried whereIn but I think it checks if any values exist in the table.

This is what I have done currently:

$v = ["value1", "value2", "value3"];

$options = Options::whereIn('value', $v)->get();

if ($options->count() != count($v)) {
//something must be missing
}

This works, but I wonder if there is a better way? The table has millions of records so I'd like to do only 1 query if possible.

Thanks!

2 Answers

The answer in the comments by justcarty is technically correct, but you can reduce the load by not pulling in the options if you don't intend to use them.

if (Option::whereIn('value', [...])->count() != count([...])) {
    //perform action
}

Also note, as justcarty mentioned, this won't work if you have multiple occurrences of a value in your database, but you can get around this by adding DISTINCT clause to your query.

if (Option::distinct(['value'])->whereIn('value', [...])->count() != count([...])) {
    //perform action
}

whereIn check specifically for that one value in the arrays.

You can try this:

$search_values = ['value1', 'value2', 'value3'];
$found = true;
foreach ($search_values as $search) {
    if (!Search::where('column', $search)->first()) {
        $found = false;
    }
}

if (!$found) {
    // Something must be missing
}
Related