Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select custom columns from Laravel belongsToMany relation

Im trying to select only specific attributes on the many-to-many relation users, just like in one-to-one. But using select() on belongsToMany() seem to be ignored and i'm still getting all the User attributes.

class Computer extends Eloquent {
    public function users() {
        return $this->belongsToMany("User")->select("email");
    }

    public function admin() {
        return $this->hasOne("User")->select("email");
    }
}

Computer::with("users")->get();

Is there a way of filtering only specified columns from related entity with belongsToMany()?

like image 458
Greegus Avatar asked May 17 '14 09:05

Greegus


2 Answers

Yes, you actually can.

Computer::with("users")->get(array('column_name1','column_name2',...));

Be careful though if you have the same column name for both tables linked by your pivot table. In this case, you need to specify the table name in dot notation, tableName.columnName. For example if both users and computer has a column name id, you need to do :

Computer::with("users")->get(array('users.id','column_name2',...));
like image 136
John Evans Solachuk Avatar answered Nov 06 '22 23:11

John Evans Solachuk


According to Taylor Otwell it is not currently possible: https://github.com/laravel/laravel/issues/2679

I have tried to use a lists('user.email') at the end of the query but I can't make it work.

like image 1
Antoine Augusti Avatar answered Nov 06 '22 21:11

Antoine Augusti