簡體   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