1

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0
  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...

Comments

0

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.