1

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" => "me@email.com"
  "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.

MH Raihan
  • 31
  • 6
  • The loadSum relation in your model, it gets your entire model. In that relation in your model you can only select the fields that you want (option 1). The other option is to improve the auth()->user()->loadSum() call, where you only select certain fields. That's probably what you're looking for – UnderDog Dec 20 '22 at 02:50
  • @UnderDog it will be a pleasure for me if you share an example code, please. thank you :) – MH Raihan Dec 20 '22 at 05:35
  • I don't have example code, I have a great link, that shows an example: https://stackoverflow.com/a/32185643/1294911 – UnderDog Dec 20 '22 at 05:50
  • Probably not the prettiest way to do it but how about ```collect(auth()->user()->loadSum('results', 'total_questions')->loadSum('results', 'correct_answered'))->only(['results_sum_total_questions', 'results_sum_correct_answered'])```? – mzolee Dec 20 '22 at 07:57

1 Answers1

1

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();
Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85