Eloquent with eager loading返回null值数组

时间:2016-12-16 17:59:25

标签: laravel eloquent eager-loading

我正在使用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

我之前使用过急切加载,但从来没有遇到过这个奇怪的错误。我在stackoverflow中发现了一些类似的问题,其中问题存在于关系中。我弄乱了这段关系吗?

1 个答案:

答案 0 :(得分:1)

您的查询未加载评论。您需要将此关系添加到InputStream iStream=ftpClient.retrieveFileStream(ftpFile.getName()); File file = File.createTempFile("tmp", null); FileUtils.copyInputStreamToFile(iStream, file);

with()

<强>更新

在评论中,您说您遇到的问题是$question = Question::where('q_id','=',$id)->with([ 'comments', 'answers' => function($q) { $q->select('answer','aid'); }]) ->get(); ,而不是answers。在这种情况下,请尝试将密钥添加到comments

select()