繁体   English   中英

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

[英]SQLSTATE[42S22]: Column not found: 1054 Unknown column 'answers.question_id' in 'where clause'

我正在尝试建立关系
问题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

数据库中的答案表

收到此错误:

SQLSTATE [42S22]:柱未找到:1054未知列在'where子句' 'answers.question_id'(SQL:SELECT * FROM answers其中answersquestion_id = 5和answersquestion_id不为空)(查看:C:\\用户\\苛刻\\ SA1 \\资源\\意见\\问题\\ show.blade.php)

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

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

将您的代码更改为

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

尝试将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 key约束和local key约束,在您的情况下,约束必须是q_idid ,其中id是问题id(主键)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM