SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ answers.question_id”

时间:2019-03-28 06:20:03

标签: php laravel laravel-5 eloquent

我正在尝试建立关系
问题hasMany答案

Question.php

public function answers()
{
   return $this->hasMany(Answer::class);    
}

然后在show.blade.php中显示问题答案,例如:

@foreach($question->answers as $answer) 
    {{$answer->ans}} //ans is the answers body from database
@endforeach

Answers table in database

遇到此错误:

  

SQLSTATE [42S22]:找不到列:1054“ where子句”中的未知列“ answers.question_id”(SQL:从answers中选择*,其中answersquestion_id = 5和answersquestion_id不为空)(视图:C:\ Users \ harsh \ sa1 \ resources \ views \ questions \ show.blade.php)

3 个答案:

答案 0 :(得分:1)

这是因为使用laravel模型时,在使用关系时默认情况下会查找question_id。相反,您必须明确提及。 如下更改您在模型文件中的关系,

  public function answers()
  {
    return $this->hasMany(Answer::class, 'q_id', 'id');     
  }

答案 1 :(得分:0)

将代码更改为

public function answers()
{
   return $this->hasMany(Answer::class,'q_id','id');    
}

答案 2 :(得分:0)

尝试将Answer::class直接更新为您的模型类:

public function answers()
{
   return $this->hasMany('App\Models\Answer', 'q_id', 'id');    
}

或者这个:

public function answers()
    {
       return $this->hasMany('App\Answer', 'q_id', 'id');    
    }

或创建模型的任何地方。 并添加foreign keylocal key约束,在您的情况下,约束必须为q_idid,其中id是问题id(主键)。