2

In a plugin, I'd like to pull all Assets with filenames starting with a certain string (the $prefix variable, in the below examples).

It's possible to do this with a custom DbCommand:

$results = craft()->db->createCommand()
    ->select('assetfiles.*')
    ->from('assetfiles assetfiles')
    ->where(array(
        'like',
        'assetfiles.filename',
        $prefix.'%',
    ))
    ->queryAll();
$assets = AssetFileModel::populateModels($results);

However, I'd like to do this using an ElementCriteriaModel. The below doesn't work:

$assets = craft()->elements->getCriteria(ElementType::Asset, array(
    'filename' => 'LIKE "'.$prefix.'%"',
    'limit' => null,
))->find();

In the above example, is the syntax off, or is not possible to use LIKE in an ElementCriteriaModel parameter?

2

The * wildcard character should do the trick.

c.f. https://craftcms.com/docs/templating/elementcriteriamodel#parameter-value-syntax

$assets = craft()->elements->getCriteria(ElementType::Asset, array(
    'filename' => $prefix.'*',
    'limit' => null,
))->find();
1
  • Works like a charm. Thanks Michael! (I edited in a working example) Sep 1 '16 at 22:43
1

A possible workaround is to use the search parameter like this:

$assets = craft()->elements->getCriteria(ElementType::Asset, array(
    'search' => 'filename::'.$prefix.'*',
    'limit' => null,
))->find();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.