Laravel雄辩分裂查询在多个步骤 [英] Laravel eloquent split query in multiple steps

查看:131
本文介绍了Laravel雄辩分裂查询在多个步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得标题很混乱,我会尽量解释一下这个。让我说我有一个很大的查询,用于搜索帖子,如下所示:

  $ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆