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();
Share:
14,170

Related videos on Youtube

fefe
Author by

fefe

Updated on June 04, 2022

Comments

  • fefe
    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
    fefe over 5 years
    I tried but using with paginate does not brings any result
  • FGDeveloper
    FGDeveloper over 5 years
    You can try whereHas method.
  • fefe
    fefe over 5 years
    thanks! that was I forgot to include the relation id