Framework: Eloquent Eager Loading Infinite Recursion

Created on 22 Feb 2017  路  3Comments  路  Source: laravel/framework

  • Laravel Version: 5.2
  • PHP Version: 5.5.9
  • Database Driver & Version: Mysql 5.6

Description:

If you eager load both a relationship and its inverse in both models, Eloquent infinitely eager loads eventually causing a segfault.

I understand this might be a difficult feature to implement, but I think it should at the least detect this and error out.

Additionally, is there a way to around this that doesn't involve specifying eager loading on every query?

Steps To Reproduce:

class User extends \Illuminate\Database\Eloquent\Model
{   
    protected $with = ['assignments'];

    public function assignments()
    {
        return $this->hasMany('Assignment');
    }
}

class Assignment extends \Illuminate\Database\Eloquent\Model
{
    protected $with = ['user']; // comment this out to avoid infinite eager loading

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

$assignment = Assignment::first(); // segfault

Most helpful comment

There is a without() method (tested on Laravel 5.4) https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_without

Try this:

class User extends \Illuminate\Database\Eloquent\Model
{   
    protected $with = ['assignments'];

    public function assignments()
    {
        return $this->hasMany('Assignment')->without('user');
    }
}

class Assignment extends \Illuminate\Database\Eloquent\Model
{
    protected $with = ['user']; // comment this out to avoid infinite eager loading

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


All 3 comments

I don't think it's possible given the way the builder works. Anyway please ask on the forums, I think it's a better place for this type of questions, we try to keep this repo for bug reporting only.

I apologize. I thought a segfault would be considered a bug.

There is a without() method (tested on Laravel 5.4) https://laravel.com/api/5.4/Illuminate/Database/Eloquent/Builder.html#method_without

Try this:

class User extends \Illuminate\Database\Eloquent\Model
{   
    protected $with = ['assignments'];

    public function assignments()
    {
        return $this->hasMany('Assignment')->without('user');
    }
}

class Assignment extends \Illuminate\Database\Eloquent\Model
{
    protected $with = ['user']; // comment this out to avoid infinite eager loading

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


Was this page helpful?
0 / 5 - 0 ratings

Related issues

Fuzzyma picture Fuzzyma  路  3Comments

RomainSauvaire picture RomainSauvaire  路  3Comments

shopblocks picture shopblocks  路  3Comments

kerbylav picture kerbylav  路  3Comments

Anahkiasen picture Anahkiasen  路  3Comments