In addition to the reply from @Diegosouza, it is possible to do this through the with
using the relationship name as chave
and the Closure
as a value.
Behold:
$with['role'] = function ($query) {
$query->select('id', 'name');
};
User::with($with)->get();
Important to note that in the question was asked to select only the field name
of Role
, but Laravel does the data linkage internally using the value defined in Model::getKey()
(in case the id
) of Role
.
So, whenever you went to make a select
in a relationship, it is necessary to select the fields where Laravel will assign the values.
A second example:
$with['role'] = function ($query) {
$query->select('id', 'name');
};
User::select('name', 'role_id')->with($with)->get();
In this second example, I would need to select as well role_id
, if you were to choose the User
, since internally the Laravel will relate User::$role_id
with Role::$id
;
Question asked by the app on mobile
– Wallace Maxters
You asked the question on the bus ?
– Diego Souza
Yes, on the bus, kkkkkkk
– Wallace Maxters