【问题标题】:How we get specific columns from multiple relations using With() in Laravel我们如何在 Laravel 中使用 With() 从多个关系中获取特定列
【发布时间】:2021-11-24 08:16:49
【问题描述】:

我需要来自两个关系的一些特定列。

在我的问题模型中,我有两个关系

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');
}

我试过了

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

我只得到 question_category 的列,不在 ans_options 中

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

但是当我尝试下面的代码时,ans_options 的所有列都得到了。

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

喜欢

{
  "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"
    }
  ]
}

我只需要 ans_options 中的 ac_id 和 ac_choiceTxt。我怎样才能做到这一点?

【问题讨论】:

    标签: laravel eloquent-relationship


    【解决方案1】:

    为了让 Laravel 能够加载关系,你应该选择负责该关系的外键

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

    只需将 'ac_quest_id' 添加到您的选择中。

    【讨论】:

    • 它的 ac_quest_id.. 它的工作谢谢
    【解决方案2】:
    1. 您可以在仅此字段可用的地方制作模型
    2. 从新模型中扩展当前模型(从当前模型中删除列)
    3. 在新的短模型中使用“with”

    我现在不知道其他方法...

    【讨论】:

      【解决方案3】:

      然后我们也可以在这里添加主键。它会得到相同的结果,然后这里就不需要闭包了。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-01
        • 1970-01-01
        • 2013-11-20
        • 2021-07-08
        • 2021-12-30
        • 2016-10-20
        • 2020-06-02
        相关资源
        最近更新 更多