假设我有如下查询:
$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);当第二个查询有效时,第一个查询现在也采用第二个查询的额外条件。 我很确定即使在以后的开发中,这两个查询也会非常相似,所以为了以后更好的维护,我不想复制和粘贴第一个查询。 有没有办法重用第一个查询中设置的条件而不会搞乱第一个查询?
PS我正在使用laravel 4.2
Let say I have a query like below:
$firstQueryResult = ItemModel::where('type', 'myType'); $firstQueryResult = $firstQueryResult->where('size', '>', '10'); $firstQueryResult = $firstQueryResult->where('price', '>', '10'); //many other condition..... $firstQueryResult = $firstQueryResult->paginate(10);Now, I have a very similar query, which basically is the same as the first query except one condition, so I tried to do something like this:
$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);While the second query works, first query now also take the extra condition of the second query. I am quite sure even in later development, these 2 queries will be very similar, so for better maintain in the future, I don't want to do a copy and paste of the first query. Is there a way to reuse the conditions set in first query without messing with the first query?
P.S. I am using laravel 4.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
Besides @herrjeh42 's answer, I found that using clone can prevent the problem too.
Using the above example:
$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);更多推荐
发布评论