查询生成器中不存在 Get onlyTrashed()

Get onlyTrashed() does not exist in query builder

我正在尝试从 table 条消息中获取已删除的行:

public function trash() {
    return $this->onlyTrashed()
        ->where('user_id', '=', $this->_u)
        ->orWhere('receiver', '=', $this->_u)
        ->orderBy('deleted_at', 'desc')->get();
}

我收到此错误:

Method Illuminate\Database\Query\Builder::onlyTrashed does not exist.

我检查了 Builder 和 SoftDeletes 文件中的 onlyTrashed 方法,但它不存在,我如何从消息 table 中查找已删除的消息?

我想到的唯一方法是创建不 return 消息的方法,其中 delete_at 不为空,并且仅将那些不为空的消息丢弃到 return .但我仍然想知道为什么这不起作用,因为它在 url:

的文档中

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

更多信息

是的,它在模型内部,是的,我添加了使用 SoftDeletes:

use Illuminate\Database\Eloquent\SoftDeletes; - 最上面

use SoftDeletes;打开后class

让我在这里粘贴整个模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\DB;

class Messages extends Model
{

use SoftDeletes;

protected $fillable = [
    'user_id', 'subject', 'text', 'receiver'
];

public $_u;

protected $dates = ['deleted_at'];

public function __construct() {
    $this->_u = auth()->user()->user_id; //or some id as string
}

public function trash() {
        return $this->onlyTrashed()
        ->where('user_id', '=', $this->_u)
        ->orWhere('receiver', '=', $this->_u)
        ->orderBy('deleted_at', 'desc')->get();
}

public static function trashed() {
        return self::onlyTrashed();
}
}

控制器有:

public function __construct() {
        $this->middleware('auth');
    }

public function index($field = 'trash') {
    if ($field !== "new") {
        $messages = (new Msg)->$field();
        $user = auth()->user();
        return view('pages.messages', compact('messages', 'user'));
    }
    return view('pages.messages.new', compact('messages', 'user'));
}

我也尝试调用 static,我尝试从 tinker 调用它,但仍然不断得到:

onlyTrashed() 不存在

我想你想要的是定义 trash 静态方法:

public static function trash() {
    return self::onlyTrashed()
        ->where('user_id', '=', $this->_u)
        ->orWhere('receiver', '=', $this->_u)
        ->orderBy('deleted_at', 'desc')->get();
}

然后通过以下方式调用此函数:

$messages = Messages::trash();

我进一步研究了一下,得到了这个:

来自 https://laravel.com/api/5.6/Illuminate/Database/Eloquent.html

我应该

SoftDeletesTrait

但我有

SoftDeletes

。在 softdeletestrait 中我们有 onlyTrashed 方法,但在 SoftDeletes 中我们没有。

所以我从这个页面复制了那个方法: https://github.com/laravel/framework/blob/7d9e7068c49f945385673014d4cba4de28accd5e/src/Illuminate/Database/Eloquent/SoftDeletingTrait.php#L119

并将其添加到 SoftDeletes class,现在它可以正常工作了。我还没找到为什么它不存在于 SoftDeletes class 中所以如果有人发现请告诉我们!

你必须调用父构造函数:

public function __construct() {
    parent::__construct();

    $this->_u = auth()->user()->user_id;
}

这应该有效

# YourModelController.php
    /**
     * Show only trashed 
     *
     * @return \Illuminate\Http\Response
     */
    public function trashed()
    {
...
        $trashed = YourModel::onlyTrashed()->get();
...
    }