skip to Main Content

Laravel with does not work currently next to get method when get has argument

I have two table that has one-to-many relationship.
enter image description here

I wrote this code:

Page::with('user:id,name')->get();

enter image description here

that work currently, but I want specific columns from pages table (such as title and body) so I wrote this code:

Page::with('user:id,name')->get(['title', 'body']);

But user will be null

enter image description here

2

Answers


  1. Use select() and you need to add foreign key also

    Page::with('user:id,name'=> function($query) { $query->select('title','body','UserId'); }])->get();   // If foreign key is `UserId` you should use your column name here
    
    Login or Signup to reply.
  2. You have to select the user_id field from pages. That is the field that is used to then get the Users associated with all the Pages that the query would return. It is separate queries. How can Eloquent do a query to get all the Users that the Posts belong to if there is no user_id field to use?

    Page::with('user:id,name')->get(['title', 'body', 'user_id']);
    

    This would mean all the returned Page results/objects would have a user_id column that it can then pluck from the Collection to then do a query to load all the Users and then match them back to their parents.

    The get method is defining your SELECT, as this is the definition of IlluminateDatabaseEloquentBuilder@get:

    public function get($columns = ['*'])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search