【问题标题】:Laravel Query Builder - Need to modify query result [duplicate]Laravel Query Builder - 需要修改查询结果[重复]
【发布时间】:2021-05-22 16:13:57
【问题描述】:

我创建了一个非常简单的查询,但是 laravel 构建器添加了额外的查询,我想删除它。

\DB::enableQueryLog();
  App\Proj::whereNotNull('deleted_at')->paginate(20);
dd(\DB::getQueryLog());

从中得出的查询如下:

select * from `projs` where `deleted_at` is not null and `projs`.`deleted_at` is null

要获得好的结果,需要的查询是:

select * from `projs` where `deleted_at` is not null

查询结果语句中没有'and ...'。

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    您的Proj 模型可能使用SoftDeletes Trait,因此默认添加deleted_at is not null 部分。

    获取已删除的类似:

    App\Proj::onlyTrashed()->paginate(20)
    

    请看这里https://laravel.com/docs/8.x/eloquent#retrieving-only-soft-deleted-models

    【讨论】:

    • 感谢您的反馈,但我如何才能获得仅包含已标记为已删除的记录的列表?
    • 刚刚修改了我的答案,以为你想要不被删除的。
    【解决方案2】:

    要获取软删除的 Proj 条目,请使用 onlyTrashed()

    \DB::enableQueryLog();
      App\Proj::onlyTrashed()->paginate(20);
    dd(\DB::getQueryLog());
    

    如果您想在查询中包含软删除的内容,请使用withTrashed()

    App\Proj::withTrashed()->paginate(20);
    

    【讨论】:

      【解决方案3】:

      不要使用 whereNotNull('deleted_at') 因为如果你使用软删除,laravel 会自动运行它

      【讨论】:

      • 感谢您的反馈,但我如何才能获得仅删除的列表?
      • 这是作为查询构建器的完美答案。因为通常不能将“null”视为所有数据库可能无法识别它。所以 whereNotNull() 是检查字段是否为“null”的正确选择
      猜你喜欢
      • 2019-10-31
      • 2019-02-10
      • 2019-04-19
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 2016-07-25
      • 2016-05-12
      • 2023-04-05
      相关资源
      最近更新 更多