Patrick Reck
Patrick Reck

Reputation: 11374

Inner join single column using Eloquent

I am trying to get a single column of an inner joined model.

$items = Item::with('brand')->get();

This gives me the whole brand object as well, but I only want brand.brand_name

$items = Item::with('brand.brand_name')->get();

Didn´t work for me.

How can I achieve this?

Upvotes: 1

Views: 135

Answers (2)

Ganesh Jogam
Ganesh Jogam

Reputation: 3151

Try this:

  $items = Item::with(array('brand'=>function($query){
          $query->select('name');
  }))->get();

Upvotes: 1

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

This will get related models (another query) with just the column you want (an id, see below):

$items = Item::with(['brand' => function ($q) {
   $q->select('id','brand_name'); // id is required always to match relations
                                  // it it was hasMany/hasOne also parent_id would be required
}])->get();
// return collection of Item models and related Brand models. 
// You can call $item->brand->brand_name on each model

On the other hand you can simply join what you need:

$items = Item::join('brands', 'brands.id', '=', 'items.brand_id')
   ->get(['items.*','brands.brand_name']);
// returns collection of Item models, each having $item->brand_name property added.

I'm guessing Item belongsTo Brand, table names are items and brands. If not, edit those values accordingly.

Upvotes: 2

Related Questions