重用Yii2查询

时间:2018-07-27 02:33:15

标签: php yii2

我正在尝试重用查询,但是失败。

在我的方法中,我有:

Excel.WorksheetFunction.IsNumber

现在,第一个(public function getPacked($from, $to){ $initquery = RealTimeTblTrucks::find() ->leftJoin('tbl_truck_history','tbl_truck_history.truck_id=tbl_trucks.id') ->where(["between","tbl_truck_history.created_at",$from,$to]) ->andWhere(["tbl_truck_history.status"=>20]); $data = []; $data[SELF] =$initquery ->andWhere(["tbl_trucks.truck_category"=>28]) ->count(); $data[NORMAL] = $initquery->andWhere(["tbl_trucks.truck_category"=>27]) ->count(); $data[BULKER] = $initquery->andWhere(['in', 'tbl_trucks.truck_category', [26,34]]) ->count(); return $data; } )返回正确的信息,但接下来的$data[SELF]NORMAL未返回正确的信息。

当我检查原始查询时,我可以看到后两个受第一个查询的影响,因此BULKER处的新查询包含对$data[NORMAL]的检查,该检查仅应在第一个数组项(truck_category = 20)。

如何重构它使其起作用?

1 个答案:

答案 0 :(得分:2)

clone在创建新对象方面的优势是,所有属性都将被复制到新对象中,而不是重置它们。当您使用查询生成器时,这非常有用。

public function getPacked($from, $to) {

   $initquery = RealTimeTblTrucks::find()
    ->leftJoin('tbl_truck_history','tbl_truck_history.truck_id=tbl_trucks.id')
    ->where(["between","tbl_truck_history.created_at",$from,$to])
    ->andWhere(["tbl_truck_history.status"=>20]);

   $data = [];
   $querySelf = clone $initquery;
   $data[SELF] = $querySelf
    ->andWhere(["tbl_trucks.truck_category"=>28])
    ->count();

   $queryNormal = clone $initquery;
   $data[NORMAL] = $queryNormal->andWhere(["tbl_trucks.truck_category"=>27])
    ->count();

   $queryBulker = clone $initquery;
   $data[BULKER]  = $queryBulker->andWhere(['in', 'tbl_trucks.truck_category', [26,34]])
    ->count();

   return $data;
}

引用Yii2 clone detail