Laravel 克隆查询字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27625411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel cloning query string
提问by Bri
Is it possible to clone a query string so I can write it once and make alterations a long the way without affection other results?
是否可以克隆一个查询字符串,以便我可以编写一次并在不影响其他结果的情况下进行很长时间的更改?
$query = DB::table('users')
->where('id', '=', '123');
$queryGet = $query;
$queryPaginate = $query;
$queryCount = $query;
if(Input::has('get'))
$queryGet = $queryGet->get();
if(Input::has('paginate'))
$queryPaginate = $queryPaginate->paginate(25);
if(Input::has('count'))
$queryCount = $queryCount->count(DB::raw('Distinct users.*'));
Because right now, the paginate will alter the first get().
因为现在,分页将改变第一个 get()。
Thanks
谢谢
回答by mopo922
You had the vocabulary exactly right :) In PHP5+, try cloning:
你的词汇完全正确:) 在 PHP5+ 中,尝试克隆:
<?php
$queryGet = clone $query;
$queryPaginate = clone $query;
$queryCount = clone $query;
回答by Nazareno Lorenzo
Mopo922 answer is the right way to do this on Laravel >= 4.1. But, in previous versions, the query doesn't "deep clone", and would produce unexpected results, as the main query is stored in a child Query
object, not in the mail Builder
.
Mopo922 答案是在 Laravel >= 4.1 上执行此操作的正确方法。但是,在以前的版本中,查询不会“深度克隆”,并且会产生意外结果,因为主查询存储在子Query
对象中,而不是邮件中Builder
。
To avoid this bug, you can use:
为避免此错误,您可以使用:
$newClone = new \Illuminate\Database\Eloquent\Builder(clone $builder->getQuery());
You can see this bug/fix story on: https://github.com/laravel/framework/issues/1336
您可以在以下位置查看此错误/修复故事:https: //github.com/laravel/framework/issues/1336