Skip to content

Unable to disable eager loading for relations specified via $with using without() #30007

@spaceemotion

Description

@spaceemotion
  • 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions