有没有办法在雄辩的Laravel中使用以前的查询条件进一步查询?

时间:2016-06-24 06:20:48

标签: php mysql laravel laravel-4 eloquent

假设我有如下查询:

$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);

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

[DllImport("winmm.dll")]
public static extern uint mciSendString( 
  string lpstrCommand, lpstrReturnString, uint uReturnLength, uint hWndCallback);

mciSendString(@"close temp_alias", null, 0, 0);   
mciSendString(@"open ""music.mp3"" alias temp_alias", null, 0, 0);   
mciSendString("play temp_alias repeat", null, 0, 0); 

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

P.S。我正在使用laravel 4.2

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

除了@ 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);