Laravel雄辩分裂查询在多个步骤 [英] Laravel eloquent split query in multiple steps
问题描述
$ posts = Post :: select(' ..')
- > leftJoin('...')
- > leftJoin('...')
- >其中('...')
- > orWhere('...')
- > orderBy('...')
- > orderBy('...')
- > ; groupBy('...')
- > with('...')
- > paginate(8);
我如何拆分这个查询?例如:
$ posts = Post :: select('...')
- > leftJoin '...')
- > leftJoin('...')
$ posts-> where('...')
- > orWhere ( '...');
$ posts-> orderBy('...')
- > orderBy('...')
- > groupBy('...' );
$ posts-> with('...')
- > paginate(8);
我使用Laravel 4.2和我尝试了几件事(包括这篇文章),但是我无法让它工作。我需要这个来搜索和过滤帖子。
首先创建一个新的模型实例并将其设置为一个变量,使用该变量构建查询,然后以 get()
结束:
$ posts = new Post;
$ posts = $ posts-> where('...');
$ posts = $ posts-> orWhere('...');
$ posts = $ posts-> orderBy('...');
...
$ posts = $ posts-> get();
尽管如此,您可以使用查询范围来简化事情和一些结构良好的关系方法。
I think the title is quite confusing, I will try to explain this as good as possible. Lets say I have quite a big query for searching posts, something like this:
$posts = Post::select('...')
->leftJoin('...')
->leftJoin('...')
->where('...')
->orWhere('...')
->orderBy('...')
->orderBy('...')
->groupBy('...')
->with('...')
->paginate(8);
How can I split this query? For example:
$posts = Post::select('...')
->leftJoin('...')
->leftJoin('...')
$posts->where('...')
->orWhere('...');
$posts->orderBy('...')
->orderBy('...')
->groupBy('...');
$posts->with('...')
->paginate(8);
Im using Laravel 4.2 and I tried several things (including this post), but I can't get it to work. I need this for searching and filtering posts.
Start by creating a new instance of your model and seting it to a variable, build your query using that variable, and then end with a get()
:
$posts = new Post;
$posts = $posts->where('...');
$posts = $posts->orWhere('...');
$posts = $posts->orderBy('...');
...
$posts = $posts->get();
Rather than doing all this chaining, though, you can probably streamline things quite a bit by using query scopes and some well-structured relation methods.
这篇关于Laravel雄辩分裂查询在多个步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!