Home > OS >  Laravel LoadSum() base on relation return also model data, how can I prevent it?
Laravel LoadSum() base on relation return also model data, how can I prevent it?

Time:12-21

I've faced an issue. When I tried to loadSum results based on relations, it also return the model data also. How can I archive only specific data? This is my query.

auth()->user()->loadSum('results', 'total_questions')->loadSum('results', 'correct_answered')

what I get here.

 [
  "id" => 1
  "first_name" => "MH"
  "last_name" => "Raihan"
  "email" => "[email protected]"
  "email_verified_at" => "2022-12-15T11:10:20.000000Z"
  "photo_path" => null
  "gender" => "male"
  "birthday" => "2033-08-25T00:00:00.000000Z"
  "country" => "Tajikistan"
  "state" => "Alaska"
  "city" => "Doylefurt"
  "phone" => "908.544.1746"
  "address" => """
    919 Johns Branch Apt. 486
    Batztown, MN 84553-3233
    """
  "postcode" => "80799"
  "active" => true
  "deleted_at" => null
  "created_at" => "2022-12-15T11:10:20.000000Z"
  "updated_at" => "2022-12-18T14:46:00.000000Z"
  "results_sum_total_questions" => "156"
  "results_sum_correct_answered" => "35"
]

What I want to expect


[
    "results_sum_total_questions" => "156"
  "results_sum_correct_answered" => "35"
]

thank you


collect(auth()->user()->loadSum('results', 'total_questions'))
->map(fn($result) => ["results_sum_total_questions" => $result->results_sum_total_questions]);


I've tried to filter data, but it does not work this way. I do not find on clue yet to solve the issue.

CodePudding user response:

use only() with it

$sums = auth()->user()
    ->loadSum('results', 'total_questions')
    ->loadSum('results', 'correct_answered')
    ->only(['results_sum_total_questions', 'results_sum_correct_answered']);

$data = $sums->toArray();
  • Related