laravel/framework — pull request #3901 by daftspunk (2014-03-17 10:05:28+00:00)
Title: [Proposal] Add ability to limit and order unions

There is no streamlined method to to sort or limit a union query. Eg:

```
$query1->union($query2)->orderBy('foo');
```

This sorts $query1, not the union. This is accurate and useful only if the query was also limit()'ed.

From MySQL Docs.

*... use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows.*

But I digress, there is no method I can see for applying a limit and order by to the *union itself*.

**Desired SQL:**

```(query 1 sql) union (query 2 sql) order by foo```

**Actual SQL:**

```(query 1 sql order by foo) union (query 2 sql)```

**Current solution (which is pretty bad):**

```
$result = DB::select(DB::raw($query1->toSql() . ' ORDER BY foo'), $query1->getBindings());
```

**Proposed solution**:

```
$query1->union($query2)->orderUnionBy('foo');
$query1->union($query2)->limitUnion(7);
```

Let me know if this is acceptable and I will write unit tests and docs for it.

Cheers