【问题标题】:Is there a way to further query using the previous query conditions in eloquent of Laravel?有没有办法在 Laravel 的 eloquent 中使用之前的查询条件进一步查询?
【发布时间】:2016-10-26 16:23:42
【问题描述】:

假设我有如下查询:

$firstQueryResult = ItemModel::where('type', 'myType');
$firstQueryResult = $firstQueryResult->where('size', '>', '10');
$firstQueryResult = $firstQueryResult->where('price', '>', '10');
//many other condition.....
$firstQueryResult = $firstQueryResult->paginate(10);

现在,我有一个非常相似的查询,除了一个条件之外,它基本上与第一个查询相同,所以我尝试做这样的事情:

$firstQueryResult = ItemModel::where('type', 'myType');
$firstQueryResult = $firstQueryResult->where('size', '>', '10');
$firstQueryResult = $firstQueryResult->where('price', '>', '10');
//many other condition.....
$secondQueryResult = $firstQueryResult->where('special', 'true')->count();
$firstQueryResult = $firstQueryResult->paginate(10);

虽然第二个查询有效,但第一个查询现在也采用第二个查询的额外条件。我很确定即使在以后的开发中,这两个查询也会非常相似,所以为了以后更好的维护,我不想复制和粘贴第一个查询。有没有办法在不弄乱第一个查询的情况下重用第一个查询中设置的条件?

附:我正在使用 laravel 4.2

【问题讨论】:

    标签: php mysql laravel laravel-4 eloquent


    【解决方案1】:

    除了@herrjeh42 的回答,我发现使用克隆也可以防止这个问题。

    使用上面的例子:

    $firstQueryResult = ItemModel::where('type', 'myType');
    $firstQueryResult = $firstQueryResult->where('size', '>', '10');
    $firstQueryResult = $firstQueryResult->where('price', '>', '10');
    //many other condition.....
    $secondQueryResult = clone $firstQueryResult;
    $secondQueryResult = $secondQueryResult->where('special', 'true')->count();
    $firstQueryResult = $firstQueryResult->paginate(10);
    

    【讨论】:

      【解决方案2】:

      您可以像这样将查询粘合在一起并重用查询部分:

      public function getItem() {
          $query = ItemModel::where('type', 'myType');
          $query = $this->queryPriceSize($query);
          //... paginate...
      }
      
      protected function queryPriceSize($query) {
          $query->where('size', '>', '10');
          $query->where('price', '>', '10');
          return $query;
      }
      

      另一个选项是查询范围,如下所述: https://laravel.com/docs/4.2/eloquent#query-scopes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-15
        • 2020-08-15
        • 2018-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多