سؤال

Currently, when I'm retrieving the 'messages', it is presenting the n+1 issue:

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

This sometimes is replicated over 100+ times!

Controller function:

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

Alert Model:

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

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

Message Model:

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

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

If I use the following line of code, I can see the MYSQL is correct, but it then can't find the location method:

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

select * from messages where messages.alert_id in ('21', '42')

I think it maybe a relationship issue, but I'm unsure of how to resolve it. Any help would be hugely appreciated.

هل كانت مفيدة؟

المحلول

Maybe I didn't understand but I'm thinking that you are trying to get an Alert with its messages and its location. I would do:

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

to use eager loading on messages and location for your Alert.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top