laravel / framework

The Laravel Framework.
https://laravel.com
MIT License
32.36k stars 10.97k forks source link

Improve how clauses for related model columns are specified. #1301

Closed atrauzzi closed 11 years ago

atrauzzi commented 11 years ago

I'm looking to filter results of a particular model based on whether there is a match in a relation it has.

The code I was hoping to write would look something like this:

$query->whereIn('permissions.name', $this->permissions);

Simply put, this would conveniently add to the query a join and a whereIn clause that uses the configured relation permissions.

While I know I could write out a join manually, I wasn't able to find anywhere in the L4 documentation or on IRC a shorthand way to accomplish this. I was thinking this might be a nice expressive way to reduce the amount of code needed for situations like this.

danharper commented 11 years ago

Had this problem today, the solution is (context):

Task::select('tasks.*')
    ->join('properties', 'properties.id', '=', 'tasks.property_id')
    ->where('properties.town', 'Portsmouth')
    ->where('tasks.state', 'Active')
    ->get();

Compare to how it's handled in FuelPHP:

// FuelPHP
Model_Task::find()
    ->related('property')
    ->where('property.town', 'Portsmouth')
    ->where('state', 'Active')
    ->get();

I think having a similar related() method for Eloquent would be ideal. It'd perform the join and set the select() with only the parent model's columns. And when setting a where(), if the column field (first arg) doesn't contain a ., it can be assumed it belongs to the parent model.

Or even having the related() method optional, and have the where intelligently guess at the correct related model?

taylorotwell commented 11 years ago

This will be solved if we support constraints on the has method, which there is a pull request for.