Laravel-删除整个收藏 [英] Laravel - delete whole collection

查看:54
本文介绍了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(); 

这篇关于Laravel-删除整个收藏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆