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

Time:11-25

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

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?

CodePudding user response:

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.

CodePudding user response:

  1. You can make model where available only this fields
  2. Extend current model from new (with removing columns from curent)
  3. use "with" from new short model

I don't know another way at now...

CodePudding user response:

Then we can add the primary key here also. It will get the same result and then no need of closures here.

Questions::with('questionCategory:cat_id,cat_value',
   'ans_options:ac_id,ac_choiceTxt,ac_quest_id')
 ->get();
  • Related