我正在尝试建立关系
问题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:从
answers
中选择*,其中answers
。question_id
= 5和answers
。question_id
不为空)(视图:C:\ Users \ harsh \ sa1 \ resources \ views \ questions \ show.blade.php)
答案 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 key
和local key
约束,在您的情况下,约束必须为q_id
和id
,其中id是问题id(主键)。