Laravel eloquent split query in multiple steps

2020-07-14 09:48发布

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.

1条回答
【Aperson】
2楼-- · 2020-07-14 10:28

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.

查看更多
登录 后发表回答