【问题标题】:Fetching only the soft deleted records仅获取软删除的记录
【发布时间】:2017-05-19 22:44:54
【问题描述】:

我创建了一个方法来仅获取我的 LessonsController 中软删除的课程

我没有得到我的课程控制器应该是什么路线

<?php

namespace App\Http\Controllers;

use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;

class LessonsController extends ApiController 
{

    protected $lessonTransformer;

    function __construct(LessonTransformer $lessonTransformer) 
    {
        $this->lessonTransformer = $lessonTransformer;
    }

    //fetch all and pass a metadata 'data' 
    public function index() 
    {
        $lessons = Lesson::all();

        return $this->respond([
            'data' => $this->lessonTransformer->transformCollection($lessons->all())
        ]);
    }

    //delete a lesson by id
    public function destroy($id)
    {   
        $dlesson = Lesson::find(input::get('id'));

        if(! $dlesson) {
            return $this->respondNotFound();
        }

        $dlesson->delete();

        return $this->respondDeleted('Lesson deleted successfully');
    }

    public function deletedLessons() 
    {
        $deleted_lessons = Lesson::onlyTrashed()->get();

        return $this->respond([
            'data' => $this->lessonTransformer->transformCollection($lessons->all())
        ]);
    }    

}

我尝试过删除记录,例如 http://localhost:8000/api/v1/lessons/11

谢谢

【问题讨论】:

    标签: php laravel api laravel-5.3


    【解决方案1】:

    确保:

    • 您在迁移中使用了softDeletes() 方法并执行了此迁移
    • 你在模型中使用了SoftDeletes trait
    • 您已将deleted_at 添加到模型中的$dates 属性

    https://laravel.com/docs/5.3/eloquent#soft-deleting

    完成所有操作后,您的查询将正常工作,并且只会返回软删除的课程:

    $deleted_lessons = Lesson::onlyTrashed()->get();
    

    【讨论】:

    • 我已经做了所有这些,如果我将 index() 替换为 Lesson::all()Lesson::onlyTrashed()-&gt;get(); 我能够得到结果,但是我如何在单独的方法中而不是在 @ 987654330@
    • 您是说完全相同的代码在index() 中有效,但在其他方法中无效?
    • 是的,我怀疑如果获取 api/v1/lessons 我会得到所有的课程期望删除一个很好但删除的课程我应该使用哪个路线跨度>
    • 检查dd(Lesson::onlyTrashed()-&gt;get());index() 和其他一些方法中的结果。我相信它会返回相同的结果。如果结果相同,则问题出在其他地方。也许问题出在转换方法上。
    猜你喜欢
    • 1970-01-01
    • 2010-09-09
    • 2018-06-20
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多