laravel/laravel — pull request #874 by franzliedke (2012-06-28 15:34:49+00:00)
Title: [Eloquent] Constraining eager loads only allows WHERE clauses

With Eloquent, eager loads [can be constrained](http://laravel.com/docs/database/eloquent#constraining-eager-loads) quite nicely.

However, I found out that this only works for WHERE clauses, all other options added to the query are ignored.

I've traced this back to this code in the Query class:

/**
* Add a nested where condition to the query.
*
* @param Closure $callback
* @param string $connector
* @return Query
*/
public function where_nested($callback, $connector = 'AND')
{
$type = 'where_nested';

// To handle a nested where statement, we will actually instantiate a new
// Query instance and run the callback over that instance, which will
// allow the developer to have a fresh query instance
$query = new Query($this->connection, $this->grammar, $this->from);

call_user_func($callback, $query);

// Once the callback has been run on the query, we will store the nested
// query instance on the where clause array so that it's passed to the
// query's query grammar instance when building.
if ($query->wheres !== null)
{
$this->wheres[] = compact('type', 'query', 'connector');
}

$this->bindings = array_merge($this->bindings, $query->bindings);

return $this;
}

As seen here, the constraints are applied on an entirely new query object, of which only the `$wheres` array will then be applied to our eager query.
I don't see why the callback could not just be applied to the actualy query object instead - if the user decides to mess with stuff they should rather not mess with, it's their fault, I think. Thus my example implementation on how to fix this. :)

This seems to be the only thing keeping me from implementing even rather complex queries with Eloquent - it would be great if this could be fixed (or at least explained).

---

Signed-off-by: Franz Liedke