![](/img/trans.png)
[英]SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' Id is null
[英]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
其中answers
。question_id
= 5和answers
。question_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_id
和id
,其中id是問題id(主鍵)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.