【发布时间】:2016-12-16 17:59:25
【问题描述】:
我正在使用 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');
}
}
问题标签:
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 中发现了一些类似的问题,问题出在关系中。我是不是把关系搞砸了。
【问题讨论】:
-
不要懒惰地正确命名你的钥匙,你不会有问题。
-
会记得@Kyslik
标签: laravel eloquent eager-loading