I'm trying to make a relation
Question hasMany
Answer
Question.php
public function answers()
{
return $this->hasMany(Answer::class);
}
then displaying Answers for a Question in show.blade.php like:
@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)
This is because of the laravel model look for the question_id by default when you use a relation. 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:
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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.