Skip to content

[5.4] Adds ability to eager load counts via property - #19154

Merged
taylorotwell merged 3 commits into
laravel:5.4from
regularlabs:patch-2
May 11, 2017
Merged

[5.4] Adds ability to eager load counts via property#19154
taylorotwell merged 3 commits into
laravel:5.4from
regularlabs:patch-2

Conversation

@regularlabs

Copy link
Copy Markdown
Contributor

This PR adds the ability to eager load counts via the protected property $withCount in the same way you can eager load relations with $with.
Like:

class FooBar extends \Illuminate\Database\Eloquent\Model
{
    protected $with      = ['foo', 'bar'];
    protected $withCount = ['baz', 'qux'];

    ...
}

This PR adds the ability to eager load counts via the protected property `$withCount` in the same way you can eager load relations with `$with`.
Like:
```
class FooBar extends \Illuminate\Database\Eloquent\Model
{
    protected $with      = ['foo', 'bar'];
    protected $withCount = ['baz', 'qux'];

    ...
}
```
@tillkruss tillkruss changed the title Adds ability to eager load counts via property [5.4] Adds ability to eager load counts via property May 11, 2017
@tillkruss

Copy link
Copy Markdown
Contributor

Tests are failing.

@regularlabs

Copy link
Copy Markdown
Contributor Author

To pass the checks I have also added an early return in the withCount method, so that it does not do anything to the query builder when the passed relations is empty.

@taylorotwell
taylorotwell merged commit c4f589e into laravel:5.4 May 11, 2017
@regularlabs
regularlabs deleted the patch-2 branch May 11, 2017 21:28
@sausin

sausin commented May 13, 2017

Copy link
Copy Markdown
Contributor

@regularlabs Thanks for this! 👍

I was not able to use nested relationships the same it works with ->with('first.second'). Is this a possibility? The name convention system could go follow the same setup and be something like first_second_count

The error that I get with the current implementation for the above example is:

BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::first.second()'

@decadence

Copy link
Copy Markdown
Contributor

@sausin It just uses withCount method which doesn't support nested relations.

@sausin

sausin commented May 13, 2017

Copy link
Copy Markdown
Contributor

@decadence Thanks for clearing it up! Should've checked the changes properly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants