![](/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.