Summer Sale! All accounts are 50% off this week.

taijuten's avatar

Lazy Loading appears not to be working for one subresource

Hey guys, I'm pulling my hair out over one particular issue. I'm sure the problem / solution is incredibly simple, but I don't seem to be seeing it.

I'm using Fractal (https://github.com/thephpleague/fractal) for a Laravel-based API. I'm also using Lazy Loading on "include"d models.

Very simply, I have a relationship, which appears to be having an N+1 problem.

The problem appears to be my Slot->Booking, relationship, as when removing this nested resource from my included payload, I get significantly (~90%) fewer SQL queries.

Slot Model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Slot extends Model
{
    use SoftDeletes;
        protected $fillable = ['capacity', 'starts_at', 'ends_at', 'created_at', 'updated_at', 'group_id', 'session_id'];
        protected $dates = ['deleted_at', 'starts_at', 'ends_at'];

    public function group()
    {
        return $this->belongsTo('App\Group');
    }

    public function bookings() {
        return $this->belongsToMany('App\Booking');
    }

    public function bookingSlots() {
        return $this->hasMany('App\BookingSlot');
    }
}

One thing worth noting, is that the slot->booking relationship is through BookingSlot, which itself has a model (there is supplementary information stored within this model).

Interestingly, if I do slot->bookingSlots->booking I do not appear to get the N+1 issue.

Can anyone point to a reason for this happening, and if so, a workaround?

Please let me know if there would be any advantage to me posting further code.

0 likes
0 replies

Please or to participate in this conversation.