kevinabraham kevinabraham - 8 months ago 83
MySQL Question

Is there a way to select columns using eloquent one to many relationship in laravel 5.2?

I am using laravel 5.2. My Database is set up as:

ID | social_id | provider
1 | x | twitter
2 | y | facebook
3 | z | twitter

ID | social_id | some_value | another_value
1 | x | 100 | 600
2 | y | 200 | 100
3 | z | 100 | 400

My relationship for the social_logins model is set up as:

public function twitterData()
return $this->hasMany('App\Models\TwitterData', 'social_id', 'social_id');

In my controller I want to retrieve back the twitter_data on certain columns with the foreign key of social_id. So far I have tried:
$socialLogin->twitterData->select('some_value', 'another_value');
but I just get an error that reads:

BadMethodCallException in Macroable.php line 74:
Method select does not exist.

If I use a
call like
for only one column I am able to get data back but how can I make it work for multiple columns?


If lists() works for you (btw, it's depricated and removed in 5.3, use pluck() instead), then using multiple arguments should also work for you:

$socialLogin->twitterData->pluck('some_column', 'another_column');

Also, you can try to pass columns in get() method to get only columns you want to get:

$data = $socialLogin->with('twitterData')->get(['some_column', 'another_column']);