framework: Unable to disable eager loading for relations specified via $with using without()

  • Laravel Version: 6.0.3
  • PHP Version: 7.1.24 (also with 7.3)
  • Database Driver & Version: MySQL 5.7.24

Description:

When eager loading a relationship (see example below), I am unable to disable this behavior using:

->without('items.event')

A “fix” that works, but is counter-intuitive is:

->with(['items' => function ($related) {
  $related->without('event');
}])

It looks like the nested, eager loaded query does not take the parent scope into account when deciding which relationships to query.

Steps To Reproduce:

Given the following setup:

class Event extends Model {
  public function items() {
    return $this->hasMany(Item::class);
  }
}

class Item extends Model {
  protected $with = ['event'];

  public function event() {
    return $this->belongsTo(Event::class);
  }
}

and the following query:

$items = Event::query()->with('item')->get();

It will create an additional query to load the event data back into the items.

SELECT * FROM `events`
SELECT * FROM `items` WHERE `items`.`event_id` in (1, 2)
SELECT * FROM `events` WHERE `events`.`id` in (1, 2) # <- Additional, unnecessary query

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 5
  • Comments: 15 (5 by maintainers)

Most upvoted comments

I’ve tried ->setEagerLoads([]) but that doesn’t work.

$entity = Gpu::whereRigId($rig_id)->without('rig')->get(); // Returns Rig entity within
$entity = Gpu::whereRigId($rig_id)->get(); // Returns Rig entity within
$entity = Gpu::whereRigId($rig_id)->get(); // Returns Rig entity within
return response()->json($entity);

They all return the rig entity embedded, meaning it was loaded 😕

Lumen v8.2.2 @ PHP 7.4

Laravel Version: 6.0.3
PHP Version: 7.1.24

Laravel 6.0 doesn’t even runs on PHP 7.1

Can you first please try one of the support channels below? If you can actually identify this as a bug, feel free to report back and I’ll gladly help you out and re-open this issue.

Thanks!