Vit
Vit

Reputation: 488

Get only one column from relation

I have found this: Get Specific Columns Using “With()” Function in Laravel Eloquent but nothing from there did not help.

I have users table, columns: id , name , supplier_id. Table suppliers with columns: id, name. When I call relation from Model or use eager constraints, relation is empty. When I comment(remove) constraint select(['id']) - results are present, but with all users fields.

$query = Supplier::with(['test_staff_id_only' => function ($query) {
            //$query->where('id',8); // works only for testing https://laravel.com/docs/6.x/eloquent-relationships#constraining-eager-loads
            // option 1
            $query->select(['id']); // not working , no results in // "test_staff_id_only": []
            // option 2
            //$query->raw('select id from users'); // results with all fields from users table
        }])->first();
        return $query;

In Supplier model:

public function test_staff_id_only(){
        return $this->hasMany(User::class,'supplier_id','id')
            //option 3 - if enabled, no results in this relation
            ->select(['id']);// also tried: ->selectRaw('users.id as uid from users') and ->select('users.id')
}

How can I select only id from users?

Upvotes: 2

Views: 4949

Answers (2)

OMR
OMR

Reputation: 12188

in you relation remove select(['id'])

public function test_staff_id_only(){
        return $this->hasMany(User::class,'supplier_id','id');
}

now in your code:

$query = Supplier::with(['test_staff_id_only:id,supplier_id'])->first();

Upvotes: 2

Tim Lewis
Tim Lewis

Reputation: 29258

There's a pretty simple answer actually. Define your relationship as:

public function users(){
  return $this->hasMany(User::class, 'supplier_id', 'id');
}

Now, if you call Supplier::with('users')->get(), you'll get a list of all suppliers with their users, which is close, but a bit bloated. To limit the columns returned in the relationship, use the : modifier:

$suppliersWithUserIds = Supplier::with('users:id')->get();

Now, you will have a list of Supplier models, and each $supplier->users value will only contain the ID.

Upvotes: 1

Related Questions