S
S
Sunnat Abdukhalilov2019-03-18 18:21:12
Yii
Sunnat Abdukhalilov, 2019-03-18 18:21:12

How to delete a file physically in Yii2 by linked table in a loop?

standard delete function

public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        return $this->redirect(['advbyuser']);
    }

There is a related image table from which you need to delete rows in a cycle along with pictures when deleting an ad, and at the end the pictures folder itself. Pictures
path - example: @web/upload/store/Adverts/Adverts8/
b0cd8f.jpg I know how it will work. But something can't be done

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2019-03-18
@f_society

Good afternoon.
Is there a foreign key relationship?
If it is, then when the record is deleted, the records from the image table will be deleted.
And the directory can be deleted like this:

public function actionDelete($id)
    {
        if($this->findModel($id)->delete()){
           FileHelper::removeDirectory($path_to_dir);
        }
        return $this->redirect(['advbyuser']);
    }

Or do this:
public function beforeDelete()
    {
        if(!parent::beforeDelete()){
            return false;
        }
        $path = 'path_to_dir';
        FileHelper::removeDirectory($path);
        return true;
    }

I
Ilya, 2019-03-18
Hrebet @hrebet

In the afterDelete() method; set the necessary logic of actions after deleting the entry, namely, the physical deletion of the file and its parent directories (provided that they are empty).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question