【问题标题】:Laravel: Can't delete data in one columnLaravel:无法删除一列中的数据
【发布时间】:2021-10-28 23:33:50
【问题描述】:

我有一个 API,其中将 PDF 添加到课程中并独立删除 PDF。在我的代码中,发生的情况是它删除了我要删除的 PDF 的 ID 的整行。我想要做的是通过 delete 方法使'lesson_pdf'为空。

这是我的控制器:

public function DeletePDF($id)
{

    $lesson = LessonPDF::find($id);
    if(is_null($lesson)){
        return response()->json('Record not found!', 401);
    }
    $lesson->delete();

    return response('PDF Deleted', 200);

}

我的课程PDF 模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class LessonPDF extends Model
{
    public $table = "lesson";
    use HasFactory;

    protected $fillable = [
        'lesson_pdf',
    ];

    // protected $guarded = [];
}

我的 API 路由:

Route::delete('pdf-delete/{id}',[LessonPDFController::class,'DeletePDF']);

任何我弄错的建议和想法将不胜感激。 TIA

【问题讨论】:

  • 请问,您想将lesson_pdf 保存为空 (null) 而不是从字面上删除该行?
  • 我想仅使用其课程 ID 删除 PDF 列,但在我的代码中发生的情况是,它会删除该 ID 的整行或数据。
  • delete 将运行正常的SQL 删除,因此您实际上将删除匹配的行或行...您只想执行$lesson-&gt;lesson_pdf = null; 然后$lesson-&gt;save();,或$lesson-&gt;update(['lesson_pdf' =&gt; null]);,但您的lesson_pdf 列必须是nullable,您是否在migration 中写过?
  • 哦,我明白了。是的,我的 course_pdf 可以为空。所以我只需要使用update成null,这是POST方法吗?
  • 不管是POSTPUTGET 还是别的什么,你只需要调用save中的任何一个(之前将该字段更新为null,或使用update)

标签: laravel laravel-8


【解决方案1】:

就像@matiaslauriti 已经在 cmets 中所说的那样。如果在迁移文件中可以为空,则只需将该字段更新为 null。

要删除文件,如果课程_pdf 列包含文件的确切名称, 你可以做

use Illuminate\Support\Facades\Storage;

Storage::delete('lesson_pdf.pdf');

理想情况下,您希望在将字段更新为 null 之前删除文件。所以你会做类似的事情

public function DeletePDF($id)
{

    $lesson = LessonPDF::find($id);
    if(is_null($lesson)){
        return response()->json('Record not found!', 401);
    }
    Storage::delete($lesson->lesson_pdf);
    $lesson->lesson_pdf = null;
    $lesson->save();
    
    return response('PDF Deleted', 200);

}

您还可以执行 if 语句来检查它是否在您运行数据库更新和返回响应之前被删除。如果没有,您可以抛出错误。这样你就可以确定它总是被删除。

Read here on laravel docs 了解更多

【讨论】:

  • 你知道我怎样才能在我的文件存储中删除它吗?我尝试了Storage::delete($lesson-&gt;lesson_pdf);,但它仍在文件夹 public\uploads\
  • 顺便说一句,这是一个散列文件
猜你喜欢
  • 1970-01-01
  • 2017-12-15
  • 1970-01-01
  • 2016-11-12
  • 1970-01-01
  • 2017-03-31
  • 2020-01-05
  • 1970-01-01
相关资源
最近更新 更多