Laravel with
does not work currently next to get
method when get
has argument
I have two table that has one-to-many relationship.
I wrote this code:
Page::with('user:id,name')->get();
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
2
Answers
Use
select()
and you need to add foreign key alsoYou have to select the
user_id
field frompages
. 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 nouser_id
field to use?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 yourSELECT
, as this is the definition ofIlluminateDatabaseEloquentBuilder@get
: