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

问题描述 投票:0回答:3

我正在努力建立关系 问题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:select * from answers其中answers.question_id = 5且answers.question_id不为null)(查看:C:\ Users \苛刻\ SA1 \资源\意见\问题\ show.blade.php)

php laravel laravel-5 eloquent
3个回答
1
投票

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

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

0
投票

将您的代码更改为

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

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(主键)。

© www.soinside.com 2019 - 2024. All rights reserved.