How to restrict selected columns from an eloquent relationship?

I have a concept of 3 elements that are stored in a database with relationships defined between them. Elements reflect survey responses. Tables:

results: id, enrolment_id, evaluation_id, completed (int), timestamps result_answers: id, result_id, answer_id, timestamps answers: id, answer_plain, answer_html, timestamps

I am trying to create an object that contains the following:

Results (array){
  id, enrolment_id, assessment_id, created_at
  Result_answers (array){
    Answer{
      id,answer_plain
    }
  }
}

I am using the following code:

$result = Result::where('enrolment_id', '=', $id)
    ->where('completed', '=', 1)
    ->with(['result_answers' => function($query) {
        $query->with(['answer' => function($query) {
            $query->select('id', 'answer_plain');
        }]);
    }])
    ->select(['id', 'enrolment_id', 'created_at'])
    ->get();
return response()->json($result);

Unfortunately, this gives me many fields that are not required, effectively displaying each field in each table in each of the relationships. How can I limit what is displayed? Apparently, this is a problem with result_answers, since I do not need any data from this table, but only a link to answer(which works).

->select() with(), .

.

+4
2

"--" result_answers. results_answers.

, , Eloquent, .

:

class Result extends Model {
  public function answers() {
    return $this->belongsToMany(Answer::class, 'results_answers');
  }
}

:

$results = Result::where('enrolment_id', '=', $id)
  ->where('completed', '=', 1)
  ->with(['answers' => function($query) {
        $query->select('id', 'answer_plain');
  }])
  ->select(['id', 'enrolment_id', 'created_at'])
 ->get();

:

foreach ($results as $result) {
  foreach ($result->answers as $answer) {
    var_dump($answer);
  }
}

:

return response()->json($results);

  return $results;

jsonable , , JSON , .

0

, get(), , :

$results = Result::where('enrolment_id', '=', $id)
->where('completed', '=', 1)`
  ->with(['answers' => function($query) {
    $query->get(['id', 'answer_plain']);
  }])->get(['id', 'enrolment_id', 'created_at'])
0

Source: https://habr.com/ru/post/1653663/


All Articles