php - Laravel lazy eager loading with pagination -
i'm using lazy eager loading feature of laravel's eloquent first query payments , eager loading payers each payment using ->load().
for clarification: users hasmany payers hasandbelongstomany payments
here code use (took while figure out works)
//get payments logged in user $payments = payment::wherehas('payers', function($q){ $q->where('user_id', '=', auth::user()->id); },'>=', db::raw('1')) ->get(); //lazy eager load pivot data, contains payer info each payment $payments = $payments->load(array( 'payers' => function($q){ $q->where('user_id', '=', auth::user()->id); })); currently query uses get() obtain payments. if change paginate() works lazy eager loading fails there no ->load() method pagination. means must query payments.
how can paginate query?
edit: table schema 
first, original answer, still believe can improve initial query. if have user wish find payments for, should able through simple eloquent relationship, rather directly via payment model more complicated wherehas() statement.
second, load() method lazy eager loading attached illuminate\database\eloquent\collection class. what's missing , preventing lazy loading working.
if have lazy eager load (eager loading work fine on initial query, or without pagination), you'll want wrap paginator's items in collection.
$paginator = auth::user()->payments()->paginate(10); $payments = new illuminate\database\eloquent\collection($payments->getitems()); $payments->load('payer'); (note: untested!)
essentially you're duplicating items paginator own new collection. you'll want pass both variables view, assuming want generated page links , such loaded collection.
paginator have setitems() method can overwrite original items array, don't know how impact rest of paginator methods. use caution.
original mistaken answer:
it appears you're loading payments single user. why need eager load each payer when there's 1 person, whom already have via auth::user()?
ideally, you'd have payments() relationship on user model, , load user's payments via auth::user()->payments.
Comments
Post a Comment