【问题标题】:Eloquent with eager loading returning null valued array雄辩的急切加载返回空值数组
【发布时间】: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


【解决方案1】:

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

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

更新

在 cmets 中,您说您遇到了 answers 的问题,但不是 comments。在这种情况下,尝试将密钥添加到select():

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

【讨论】:

  • 抱歉,answers 为空。已修改
  • @uttejh 因为select() 你已经删掉了外键,所以找不到关系。
猜你喜欢
  • 2013-09-22
  • 2019-09-14
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多