Laravel-删除整个收藏

问题描述:

我有文章的图片,当我更新文章时,我想检查图片是否相同,如果不是,我想删除它们,但如果可能的话,我想删除整个馆藏而没有其他图片查询,类似于我在 $ images-> delete(); 下面的代码中的内容.这是我的功能:

I have images for articles, and when I am updating article I would like to check if the images are the same, if not I would like to delete them but if it is possible I would like to delete the whole collection without another query, something like what I have in the code below $images->delete();. This is my function:

$images = Media::where('article_id', $article->id)->get();

    foreach($images as $image) {
        $article_images[] = $image->original_name;
    }

    foreach($files as $file) {
      $filePathArr = explode('/', $file);
      $fileName = array_pop($filePathArr);
      $originalFile = explode('-', $fileName);
      $originalFileName = array_pop($originalFile);
      $newFiles[] = $originalFileName;
    }

    if ($newFiles != $article_images){
      $images->delete();
    }

您只能在不进行查询的情况下从数据库中删除.

You just can't delete from database without making a query.

您将必须这样发出新请求:

You will have to make new request like this:

Media::where('article_id', $article->id)->delete();

这只是一个简单的查询,因此不应有任何性能损失.

It's just one simple query, so there shouldn't be any performance penalty.

如果我们谈论的是100个项目的集合,则可以这样优化查询:

If we are talking about collection with 100's of items, you can optimize the query like this:

Media::whereIn('id', $images->pluck('id'))->delete();