Eloquent 预加载返回空值数组

Eloquent with eager loading returning null valued array

我正在使用 laravel 5.2 并且在执行以下操作时,返回的答案为空值。

$id = Request::input('id');

    $question = Question::where('q_id','=',$id)->with(
        array('answers'=>function($query){
            $query->select('answer','aid');
        })
    )
    ->get();
    return $question;

问题模型:

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

数据库:

COMMENTS table
-qid
-comment

Question table:
-qid
-title
-body

Answers table:
-aid
-qid
-answer

我以前使用过预先加载,但从未遇到过这种奇怪的错误。我在 Whosebug 中发现了一些类似的问题,其中问题出在关系中。我搞砸了关系吗?

您的查询未加载评论。您需要将此关系添加到 with():

$question = Question::where('q_id','=',$id)->with([
    'comments',
    'answers' => function($q) {
        $q->select('answer','aid');
    }])
    ->get();

更新

在评论中您说 answers 有问题,但 comments 没有。在这种情况下,尝试将密钥添加到 select():

$query->select('answer','aid', 'qid');