ciccioassenza
ciccioassenza

Reputation: 233

laravel display only specific column from relation

I have read a few topics about this, but they managed to solve my problem partially ...

this is my controller

class DeskController extends BaseController{

public function getDeskUsers($deskId){
    $user = DeskUserList::where(function($query) use ($deskId){
        $query->where('deskId', $deskId);
    })->with('userName')->get(array('deskId'));

    if (!$user->isEmpty())
        return $user;
    return 'fail';
}

this is the model

class DeskUserList extends Eloquent {

  protected $table = 'desk_user_lists';

  public function userName(){
    return $this->belongsTo('User', 'userId')->select(array('id','userName'));
  }
}

the method getDeskUsers may returns ALL the DeskUserList table records, related with the User table record (on deskUserList.userId = User.id).

practically I want each record returned is composed of:

DeskUserList.deskId

User.userName

eg. [{"deskId":"1","user_name":antonio}]

What i get is

[{"deskId":"1","user_name":null}]

As you can see the user name is a null value...

BUT

if I edit my controller code:

->with('userName')->get(array('userId')); //using userId rather than deskId

then i get

[{"userId":"2","user_name":{"id":"2","userName":"antonio"}}]

By this way I still have two problem:

hope be clear, thanks for your time!

Upvotes: 0

Views: 1388

Answers (1)

Jarek Tkaczyk
Jarek Tkaczyk

Reputation: 81187

You need belongsToMany, no need for a model representing that pivot table.

I assume your models are Desk and User:

// Desk model
public function users()
{
 return $this->belongsToMany('User', 'desk_user_list', 'deskId', 'userId');
}

// User model
public function desks()
{
 return $this->belongsToMany('Desk', 'desk_user_list', 'userId', 'deskId');
}

Then:

$desks = Desk::with('users')->get(); // collection of desks with related users

foreach ($desks as $desk)
{
  $desk->users; // collection of users for particular desk
}

// or for single desk with id 5
$desk = Desk::with('users')->find(5);
$desk->users; // collection of users
$desk->users->first(); // single User model

Upvotes: 1

Related Questions