0

I want to get all IDs from with, at the moment I get all data (id, name, pivot, etc..)

$teacher = Teacher::where('id', $id)->with(['subjects' => function($q) {
      $q->select('id')->value('id');
}])->orderByDesc('id')->first();

I tried:

$q->pluck('id')->all();
$q->pluck('id');
$q->get('id');
$q->value('id');
$q->pluck('id')->all();

At the end result I only idee an array of ids [1, 2, 3].

Beusebiu
  • 1,433
  • 4
  • 23
  • 68
  • `$q->select('subjects.id')->value('subjects.id');` – STA Mar 11 '21 at 16:01
  • Same output.. [ { "id": 33, "pivot": { "teacher_id": 34, "subject_id": 33 } } ] – Beusebiu Mar 11 '21 at 16:02
  • Does this answer your question? [Laravel Eager Loading - Load only specific columns](https://stackoverflow.com/questions/16994253/laravel-eager-loading-load-only-specific-columns) – miken32 Mar 11 '21 at 23:07

1 Answers1

1

Most likely much easier to come at this query from the reverse. I.E. if you are after only the ids of those Subjects under a particular Teacher, grab from the Subjects table rather than a subquery at the Teacher level.

For a simple relationship, something like:

$subject_ids = Subject::where('teacher_id', $id)->pluck('id');

Or if it is a full pivot relationship you could go to the table itself, similar to:

$subject_ids = \DB::table('subject_teacher')->where('teacher_id', $id)->pluck('subject_id');

The last example assumes a lot in terms of how you set this up, but hopefully gives you an idea on how you might do this with a simpler query.

HTH

Watercayman
  • 7,970
  • 10
  • 31
  • 49