如何在方法类orm Laravel中更改密钥ID?

时间:2018-11-01 22:11:07

标签: laravel-5 eloquent

也许不可能,但是我在表中输入了问题ID和问题ID一样的单选输入答案,答案为id = 36,答案=是。我下面的代码获得了所有答案

public function getAnswer() {
        return $this->hasMany('App\Answer', 'user_id', 'id')
            ->with('question')
            ->whereHas('question.group', function($query) {
                $query->where('name', 'simple_quesion');
            });
    }

我有可以的收藏夹

#items: array:9 [▼
    0 => getAnswer {#400 ▶}
    1 => getAnswer {#401 ▶}
    2 => getAnswer {#402 ▶}

但是可以通过任何方式获取密钥并进行分配,例如

#items: array:9 [▼
        35 => getAnswer {#400 ▶}
        37 => getAnswer {#401 ▶}
        42 => getAnswer {#402 ▶}

在此方法中,公共函数getAnswer()吗?

[更新]

完整收藏

Collection {#396 ▼
  #items: array:9 [▼
    0 => getAnswer {#400 ▼
      #fillable: array:3 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [▼
        "id" => 18
        "user_id" => 11
        "answer_id" => 34
        "answer" => "YES"
      ]
      #original: array:7 [▶]
      #changes: []

我需要关键的answer_id => 34

#items: array:9 [▼
    34 => getAnswer {#400 ▼

2 个答案:

答案 0 :(得分:1)

好吧,我是如此愚蠢。这很容易。在刀片或控制器中,我可以使用:

{{ dd($user->getAnswer->pluck('answer', 'answer_id')) }}

答案 1 :(得分:0)

尝试一下:

Answer模型中,添加以下内容:

public function question(){
    return $this->belongsTo("App\Question"); //the column name of the question should be "question_id"
}

Question模型中,执行:

public function answers(){
    return $this->hasMany("App\Answer"); 
}

在您要获取问题及其答案的控制器中,您只需执行以下操作:

Question::with('answers')->all(); //assuming you want to get all the questions and their answers

希望我的回答有帮助!