Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How we get specific columns from multiple relations using With() in Laravel

I need some specific columns from two relations.

In my questions model I have two relations

public function ans_options()
{
 return $this->hasMany('App\Models\AnswerChoices', 'ac_quest_id', 'q_id');
}
public function question_category()
{

 return $this->hasOne("App\Models\Categories", 'cat_id', 'q_category');
}

I tried

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Questions::with(array(
                'questionCategory' => function($query) {$query->select('cat_id','cat_value');},
                'ans_options' => function($query1) {$query1->select('ac_id','ac_choiceTxt');}
               ))->get();

am getting only the columns of question_category not in ans_options

{
  "q_id": 349,
  "q_project_id": 140,
  "q_text": "<p>Gender</p>",
  "question_category": {
    "cat_id": 1,
    "cat_value": "normal"
  },
  "ans_options": []
}

But when I try the below code all columns of ans_options are getting.

Questions::with('questionCategory:cat_id,cat_value','ans_options')->get();

like

{
  "q_id": 349,
  "q_project_id": 140,
  "q_text": "<p>Gender</p>",
  "question_category": {
    "cat_id": 1,
    "cat_value": "normal"
  },
  "ans_options": [
    {
      "ac_id": 334,
      "ac_quest_id": 349,
      "ac_choiceTxt": "Male",
      "ac_modifiedOn": "2021-11-24T06:22:00.000000Z",
      "ac_status": "active"
    },
    {
      "ac_id": 335,
      "ac_quest_id": 349,
      "ac_choiceTxt": "Female",
      "ac_modifiedOn": "2021-11-24T06:22:00.000000Z",
      "ac_status": "active"
    }
  ]
}

I need only ac_id and ac_choiceTxt from ans_options. How can I achieve that?

>Solution :

to make Laravel able to load the relation, you should select the foreign key that responsible for that relation

Questions::with(array(
                'questionCategory' => function($query) {$query->select('cat_id','cat_value');},
                'ans_options' => function($query1) {$query1->select('ac_id','ac_choiceTxt'
,'ac_quest_id');}))->get();

just add 'ac_quest_id‘ to your select.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading