Select fields in Laravel Eloquent with relation
14,170
Solution 1
You should use:
User::select('username', 'firstname', 'lastname')->with(['periods' => function($){
$->select('jobtitle', 'user_id')->orderBy('start_date', 'desc')->limit(1);
}])->paginate(50);
instead. I've added user_id
, because probably this is the column that joins periods with users. Eloquent cannot attach valid periods to users if you don't select column used for "matching" those records
Solution 2
You can solve following method in laravel 5.5 and newer version.
User::select('username', 'firstname', 'lastname')->with('periods:jobtitle')->get();
Related videos on Youtube
Author by
fefe
Updated on June 04, 2022Comments
-
fefe almost 2 years
How can I select fields in a laravel eloquent object what I mean
User::select('username', 'firstname', 'lastname')->with(['periods' => function($){ $->select('jobtitle')->orderBy('start_date', 'desc')->limit(1); }])->paginate(50);
in may case on this query I get periods null
-
fefe over 5 yearsI tried but using with paginate does not brings any result
-
FGDeveloper over 5 yearsYou can try whereHas method.
-
fefe over 5 yearsthanks! that was I forgot to include the relation id