我正在努力建立关系
问题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
不为null)(查看:C:\ Users \苛刻\ 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(主键)。