Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel belongsToMany to return specific columns only

So I have a many to many relationship between Users and Photos via the pivot table user_photo. I use belongsToMany('Photo') in my User model. However the trouble here is that I have a dozen columns in my Photo table most I don't need (especially during a json response). So an example would be:

//Grab user #987's photos:
User::with('photos')->find(987);
//json output:
{
  id: 987,
  name: "John Appleseed",
  photos: {
    id: 5435433,
    date: ...,
    name: 'feelsgoodman.jpg',
    ....// other columns that I don't need
  }
}

Is it possible to modify this method such that Photos model will only return the accepted columns (say specified by an array ['name', 'date'])?

User.php

public function photos()
{
  return $this->belongsToMany('Photo');
}

Note: I only want to select specific columns when doing a User->belongsToMany->Photo only. When doing something like Photo::all(), yes I would want all the columns as normal.

EDIT: I've tried Get specific columns using "with()" function in Laravel Eloquent but the columns are still being selected. Also https://github.com/laravel/laravel/issues/2306

like image 778
tiffanyhwang Avatar asked Feb 08 '14 12:02

tiffanyhwang


2 Answers

You can use belongsToMany with select operation using laravel relationship.

public function photos()
{
  return $this->belongsToMany('Photo')->select(array('name', 'date'));
}
like image 90
Vivek Pandey Avatar answered Sep 28 '22 05:09

Vivek Pandey


Im assuming you have a column named user_id. Then you should be able to do the following:

public function photos()
{
    return $this->belongsToMany('Photo')->select(['id', 'user_id', 'date', 'name']);
}

You have to select, the foreign key, else it will have no way of joining it.

like image 26
jah Avatar answered Sep 28 '22 05:09

jah