为什么 getQuery 忽略软删除?

Why getQuery ignores soft deletes?

在 Laravel 中,当我使用 getQuery 函数修改基于模型的查询结果时,我得到了所有值,包括软删除。它实际上忘记了在查询中包含 and stock.deleted_at is null 。为什么?我怎样才能让它过滤掉删除的记录。

型号

class Stock extends Model
{
  use SoftDeletes;
  protected $dates = ['issue_date', 'expiry_date'];
...

查询(获取按 expiry_date 分组的股票)

$query = Stock::where('product_id', $id);
$query = $query->getQuery();
$query
    ->select(DB::raw(
        'count(*) as total, 
         DATE_FORMAT(IFNULL(`expiry_date`, "0000-00-00"),"%d-%m-%Y") AS expiry_date '
    ))
    ->groupBy('expiry_date');

$result = $query->get();

我有一个不使用 getQuery() 的想法,但在这种情况下 'issue_date' 会给我一条错误消息 "laravel Data missing"。

使用$query->toBase() instead of $query->getQuery().

$results = Stock::where('product_id', $id)->toBase()->selectRaw('
    count(*) as total, 
    DATE_FORMAT(IFNULL(`expiry_date`, "0000-00-00"),"%d-%m-%Y") AS expiry_date
')->groupBy('expiry_date')->get();

getQuery 方法只是 return 底层查询,而 toBase 首先应用所有全局范围(软删除作为全局范围实现)。


顺便说一句,您可以直接在 Eloquent 查询本身上调用 selectgroupBy

$results = Stock::where('product_id', $id)->selectRaw('
    count(*) as total, 
    DATE_FORMAT(IFNULL(`expiry_date`, "0000-00-00"),"%d-%m-%Y") AS expiry_date
')->groupBy('expiry_date')->get();

...尽管那会 return 部分 Eloquent 模型,这并不总是一个好主意。