简体   繁体   中英

Laravel 5 - return only one field from relationship

have a relationship which returns rows from a pivot table.

However I just want to return a collection of the user ids from the table.

If I have it as current:

public function followers()
{
    return $this->hasMany('App\Follower')->select(array('project_id', 'user_id'));
}

It will return the 2 fields, but if I just have the select with a single field:

public function followers()
{
    return $this->hasMany('App\Follower')->select( 'user_id');
}

It returns an an empty object.

Any ideas?

I'm guessing this function is in your Project model. When modifying the select on a relationship, you must, at a minimum, select the fields needed to match the records together.

In this case, if this in on your Project model, if you don't select the project_id from the related table, Laravel can't match up the Follower objects with the correct Project objects, since Laravel won't have any idea which Project the Follower belongs to without the foreign key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM