[英]SQLSTATE[42S22]: Column not found: 1054 Unknown column 'answers.question_id' in 'where clause'
I'm trying to make a relation 我正在尝试建立关系
Question hasMany
Answer 问题
hasMany
答案
Question.php Question.php
public function answers()
{
return $this->hasMany(Answer::class);
}
then displaying Answers for a Question in show.blade.php like: 然后在show.blade.php中显示问题的答案,例如:
@foreach($question->answers as $answer)
{{$answer->ans}} //ans is the answers body from database
@endforeach
Getting this error: 收到此错误:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'answers.question_id' in 'where clause' (SQL: select * from
answers
whereanswers
.question_id
= 5 andanswers
.question_id
is not null) (View: C:\\Users\\harsh\\sa1\\resources\\views\\questions\\show.blade.php)SQLSTATE [42S22]:柱未找到:1054未知列在'where子句' 'answers.question_id'(SQL:SELECT * FROM
answers
其中answers
。question_id
= 5和answers
。question_id
不为空)(查看:C:\\用户\\苛刻\\ SA1 \\资源\\意见\\问题\\ show.blade.php)
This is because of the laravel model look for the question_id by default when you use a relation. 这是因为laravel模型在使用关系时默认情况下会查找question_id。 instead you have to mention explicitly.
相反,您必须明确提及。 Change your relation in model file like this below,
如下更改模型文件中的关系,
public function answers()
{
return $this->hasMany(Answer::class, 'q_id', 'id');
}
change your code to 将您的代码更改为
public function answers()
{
return $this->hasMany(Answer::class,'q_id','id');
}
Try updating Answer::class
directly to your model class which can be this: 尝试将
Answer::class
直接更新为您的模型类,可以是:
public function answers()
{
return $this->hasMany('App\Models\Answer', 'q_id', 'id');
}
or this: 或这个:
public function answers()
{
return $this->hasMany('App\Answer', 'q_id', 'id');
}
or wherever you have created your model. 或创建模型的任何地方。 And add the
foreign key
and local key
constraints which in your case must be q_id
and id
where id is the question id (primary key). 并添加
foreign key
约束和local key
约束,在您的情况下,约束必须是q_id
和id
,其中id是问题id(主键)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.