Specify columns in a relationship with Laravel

1

I have a relationship of User with Role .

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

In this 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 would I specify specific columns for this relationship?

    
asked by anonymous 27.01.2017 / 10:18

2 answers

2

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

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

Another option:

User::select('role_id', 'name')->with('role', function($query){
    $query->select('id', 'name');
})
->get();
    
27.01.2017 / 11:18
1

In addition to the response from @DiegoSouza , you can do this using with using the relationship name as chave and Closure as value.

See:

$with['role'] = function ($query) {
   $query->select('id', 'name');
};

User::with($with)->get();

Note that in the question you were prompted to select only the name field of Role , however Laravel does the data relationship internally using the value defined in Model::getKey() (in this case id ) of Role .

So, whenever you were to select in a relationship, you need 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 also need to select role_id , if I were to choose the fields of User , since internally Laravel would relate User::$role_id to Role::$id ;

    
27.01.2017 / 11:32