Reputation: 184
I am using laravel 5.2 and when executing the following, I am being returned by a null value for answers.
$id = Request::input('id');
$question = Question::where('q_id','=',$id)->with(
array('answers'=>function($query){
$query->select('answer','aid');
})
)
->get();
return $question;
Question model:
class Question extends Model
{
protected $table="questions";
protected $primaryKey = 'q_id';
public function comments()
{
return $this->hasMany('App\Comments','qid','q_id');
}
public function qtags()
{
return $this->hasMany('App\Question_tags','q_id','q_id');
}
public function answers()
{
return $this->hasMany('App\Answers','qid','q_id');
}
}
Question_tags:
class Question_tags extends Model
{
protected $table="question_tags";
public function tags()
{
return $this->belongsTo('App\Tags','tag_id','tagid');
}
}
Database:
COMMENTS table
-qid
-comment
Question table:
-qid
-title
-body
Answers table:
-aid
-qid
-answer
I have used the eager loading previously but never got this wierd error. I found some similar questions in the stackoverflow where the problem being in the relationships. Did I mess up the relationships.
Upvotes: 0
Views: 1025
Reputation: 163788
Your query doesn't load comments. You need to add this relationship to with()
:
$question = Question::where('q_id','=',$id)->with([
'comments',
'answers' => function($q) {
$q->select('answer','aid');
}])
->get();
Update
In comments you said you're having problems with answers
, but not comments
. In this case try to add key to select()
:
$query->select('answer','aid', 'qid');
Upvotes: 1