Loravel's Eloquent Split Query

I think the title is rather confusing, I will try to explain it as best I can. Let's say I have a fairly large query to find messages, something like this:

$posts = Post::select('...')
           ->leftJoin('...')
           ->leftJoin('...')
           ->where('...')
           ->orWhere('...')
           ->orderBy('...')
           ->orderBy('...')
           ->groupBy('...')
           ->with('...')
           ->paginate(8);

      

How can I split this request? For example:

$posts = Post::select('...')
           ->leftJoin('...')
           ->leftJoin('...')

$posts->where('...')
      ->orWhere('...');

$posts->orderBy('...')
      ->orderBy('...')
      ->groupBy('...');

$posts->with('...')
      ->paginate(8);

      

I am using Laravel 4.2 and I have tried several things (including this post ) but I cannot get it to work. I need this for searching and filtering messages.

+3


source to share


1 answer


Start by creating a new instance of your model and setting it to a variable, build your query using that variable, and then end up with get()

:

$posts = new Post;
$posts = $posts->where('...');
$posts = $posts->orWhere('...');
$posts = $posts->orderBy('...');
...
$posts = $posts->get();

      



Instead of doing this whole chain, you can probably simplify things a bit by using query scopes and some well structured relationship methods.

+10


source







All Articles