0
votes

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

Answers table in database

Getting this error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'answers.question_id' in 'where clause' (SQL: select * from answers where answers.question_id = 5 and answers.question_id is not null) (View: C:\Users\harsh\sa1\resources\views\questions\show.blade.php)

3
please post your migrations as well - Salman Zafar
And how does your answers table look like? - kuh-chan
question_id != q_id - you need to be consistent with your naming of columns, otherwise specify it explicitly in hasMany(). Easier to just rename q_id to question_id. - Qirel
query say's question_id but your table has column q_id just change that - Gaurav Gupta
either change filed name q_id to question_id in database or specifie field name q_id in relationship - Palak Jadav

3 Answers

1
votes

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');     
  }
0
votes

change your code to

public function answers()
{
   return $this->hasMany(Answer::class,'q_id','id');    
}
0
votes

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).