在雄辩的查询中防止n + 1

时间:2014-05-11 15:32:10

标签: php laravel laravel-4 eloquent

目前,当我检索“消息”时,它会显示n+1问题:

select * from `messages` where `messages`.`alert_id` = '21'

这有时会复制超过100次!

控制器功能:

public function getIndex() {
    $alerts = Alert::with('location')
              ->where('user_id', '=', Auth::user()->id)
              ->get();
    $this->layout->content = View::make('agents.index', 
                                   array('alerts' => $alerts));
}

警报模型:

public function location()
{
    return $this->belongsTo('Location');
}

public function messages()
{
    return $this->hasMany('Message');
}

消息模型:

public function alert()
{
    return $this->belongsTo('Alert');
}

public function user()
{
    return $this->belongsTo('User');
}

如果我使用以下代码行,我可以看到MYSQL是正确的,但它无法找到location方法:

$alerts = Alert::with('messages.location')
  

messages中选择* messagesalert_id(' 21',' 42')

我认为这可能是一个关系问题,但我不确定如何解决它。任何帮助都将非常感激。

1 个答案:

答案 0 :(得分:0)

也许我没有理解,但我认为你正试图通过其消息及其位置获得警报。我愿意:

public function getIndex() {
    $alerts = Alert::with('location', 'messages')
              ->where('user_id', '=', Auth::user()->id)
              ->get();
    $this->layout->content = View::make('agents.index', 
                                   array('alerts' => $alerts));
}

对警报的消息和位置使用预先加载。