0

I'm new to Laravel and still getting my head around Eloquent. I have two models (A, B) with a many-to-many relationship (belongsToMany in both models) with the following fields:

A: id, name, text, etc..

B: id, name, description, info, etc...

A_B: id, A_id, B_id

When retrieving an object of 'A', I just want to retrieve the 'id' and 'name' of its related 'B', rather than the entire 'B' objects - as these could be large. Is a way to retrieve only specific columns from a related model, or would it be better to separate my tables so that 'id' and 'name' are on their own?

Alex
  • 45
  • 2
  • Possible duplicate of [Get specific columns using "with()" function in Laravel Eloquent](http://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent) – alexw Mar 25 '16 at 16:11

1 Answers1

0

I'm not really sure if grabbing all of the columns from table 'B' would effect speed of the query too much, but you can try this:

Model class for table 'A_B'

class A_B extends Eloquent {

    public function a(){
        $this->hasMany('A', 'id', 'a_id');
    }

    public function b(){
        $this->hasMany('B', 'id', 'b_id');
    }

}

In your model for table 'B'

class B extends Eloquent {
    //Hide fields from displaying in your query
    protected $hidden = array('description', 'info');
}

In your controller:

//Get all records with A and B
$all = A_B::with('a')->with('b')->get();

return View::make('view')->with('all', $all);

In your view:

@if($all->count() > 0)
    @foreach($all as $record)
        {{ $record->id }}
        {{ $record->name }}
    @endforeach
@else
    There are no records to be displayed
@endif
Steve Bauman
  • 8,165
  • 7
  • 40
  • 56