Skip to main content
2 of 2
deleted 28 characters in body
Brad Bell
  • 67.6k
  • 6
  • 75
  • 145

How do I delete an asset with module or plugin

I'm trying to clean-up the assets in a specific folder that aren't being used at all, i.e. aren't related to anything.

I got the list O.K. just using this

$assets = Asset::find()->volume('artists')->kind('image')->limit(50000)->ids();

$assetsToDelete = [];

foreach($assets as $asset) {
    $results = (new Query())
        ->select(['id'])
        ->from(['{{%relations}}'])
        ->where(['targetId' => $asset])
        ->orWhere(['sourceId' => $asset])
        ->all();

    if (!count($results)) {
        $assetsToDelete[]  = $asset;
    }     
}

return  $this->asJson($assetsToDelete);

Right now I'm just returning all the ids in an array but I'm hoping to find a command to delete the element AND delete the stored asset on the server

Any ideas?

Keith Mancuso
  • 2.4k
  • 17
  • 28