Specify columns in a relationship with Laravel

Asked

Viewed 493 times

1

I have a relationship of User with Role.

User::with('role')->get()

In the case, User has the columns: id, name, role_id, created_at and updated_at.

And Role has: id, name, slug, created_at, updated_at.

How do I select only name of Role ?

How I would specify specific columns of that relationship ?

  • 1

    Question asked by the app on mobile

  • You asked the question on the bus ?

  • Yes, on the bus, kkkkkkk

2 answers

2


In the model User in relationship function role() you can do select().

public function role(){
    return $this->belongsTo('App\Role')->select('name', 'id');
}

Other option:

User::select('role_id', 'name')->with('role', function($query){
    $query->select('id', 'name');
})
->get();
  • Look, it solves the problem, but particurlarmente, not to get hard code, I prefer the with with Closure.

1

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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.