Php 在雄辩的查询中阻止n+1

Php 在雄辩的查询中阻止n+1,php,laravel,laravel-4,eloquent,Php,Laravel,Laravel 4,Eloquent,目前,当我检索“消息”时,它呈现了n+1问题: 这有时会被复制100多次以上 控制器功能: public function getIndex() { $alerts = Alert::with('location') ->where('user_id', '=', Auth::user()->id) ->get(); $this->layout->content = View::make('ag

目前,当我检索“消息”时,它呈现了n+1问题:

这有时会被复制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方法:

在'21'、'42'中的messages.alert_id所在的messages中选择*


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

也许我不明白,但我认为您正在尝试获取一个带有其消息和位置的警报。我会:

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

使用即时加载消息和位置来发送警报。

@Svengali很乐意为您提供帮助$company=User::findAuth::User->id->companys->with'users.alerts.location.messages'->首先;安托万·奥古斯蒂,这有什么不起作用的原因吗?找不到messages方法?@Svengali没有你的用户模型,很难说。你想得到什么?我猜:$user=user::findAuth::user->id->with'companys','alerts','alerts.location','alerts.messages'‌​->第一再次阅读文档的这一部分:尤其是嵌套关系。用户模型:公共函数公司{return$this->belongsToMany'Company';}公共函数警报{return$this->hasMany'Alert';}
$alerts = Alert::with('messages.location')
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));
}