【问题标题】:Overriding where conditions in Laravel Query builder覆盖 Laravel 查询构建器中的 where 条件
【发布时间】:2019-01-08 14:54:17
【问题描述】:

我正在开发电子商务应用程序,我在其中获取状态为 1 的产品。 但在某些情况下,我需要获取状态为 2 或 3 的产品。

我已经覆盖了newQuery 方法并在该方法中添加了status 1 的条件。现在我想为status 2 添加另一个条件,但是当我添加这个条件时,where 子句将在该列的 SQL 查询中重复(查询生成器的默认行为)。

下面是我的代码,

public function newQuery($excludeDeleted = true) {
    return parent::newQuery($excludeDeleted)
     ->where('status', 1);                
}

当我需要获取以下状态为 2 的产品时

return $query->where('status', 2);

那么形成的查询将如下所示

select * from `products` where `status` = 1 and `status` = 2

但我需要如下查询的输出

select * from `products` where `status` = 2

请提出方法。

【问题讨论】:

标签: php laravel laravel-5 eloquent laravel-query-builder


【解决方案1】:

给newQuery函数添加一个参数并传入状态。调用 newQuery 函数时,默认状态为 1,但如果您提供参数,它将是您传递给它的任何参数。

public function newQuery($excludeDeleted = true, $status = 1) {
    return parent::newQuery($excludeDeleted)
        ->where('status', $status);                
}

编辑

这可以使用Dynamic Local Query Scope:

//Model

public function scopeStatus($query, $status = 1)
{
    return $query->where('status', $status);
}

然后像这样调用:

$result = App\MyModel::status(2)->get();
//OR To get with default "status"
$result = App\MyModel::status()->get();

【讨论】:

  • 试过了,但查询是一样的。状态将始终为 1,因为将在不传递第二个参数的情况下调用 newQuery()。当我将为状态 2 添加条件时,如何传递第二个参数。
  • 你在哪里打电话给newQuery()
  • 我在 Product 模型中定义了它。
  • 如果您想要的结果是在调用查询时指定您想要的状态,您应该在模型中制作您的函数以接受额外的参数,这个参数可以从视图中的用户传递 - >controller->通过 GET 或 POST 请求建模
  • @Nagesh 这个答案确实有效,您只需在代码的另一侧添加参数。如上面的答案所示,除非另有定义,否则默认情况下状态将始终为 1。
猜你喜欢
  • 2021-09-18
  • 2014-10-04
  • 2017-01-14
  • 2017-03-09
  • 2020-10-05
  • 2020-09-09
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
相关资源
最近更新 更多