Eloquent query with multiple withs or with with within a hirarchy

679 0 0 0

Last Updated : 2024-04-26 23:15:07

Some time, you may need to get a record with some relationship and at the same time you need to get an inner relationship to that relationship and so forth. Here is the key : $records->with(['bill', 'bill.sponsor', 'bill.sponsorSenator', 'bill.sponsor.actions']).

$records = new BillEventModel();
$records = $records->newQuery();
$records->where('eventType','federal');
$records = $records->with(['bill', 'bill.sponsor', 'bill.sponsorSenator'])->groupBy('bill_id')->orderBy('date', 'desc'); //Use this to add the relatioship and inner ones as well
$recordsCount = $records->get()->count();
$records = $records->paginate(50);

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .