hoyvoy / laravel-cross-database-subqueries

Eloquent cross database compatibility in subqueries
MIT License
103 stars 45 forks source link

whereHas() to a relationship that has a global scope with a whereHas() #9

Open reedmaniac opened 5 years ago

reedmaniac commented 5 years ago

Description:

I have discovered that if you do a whereHas() statement to a relationship and that relationship's model has a global scope that also does a whereHas(), then a loop is formed and you run out of memory and get a 500 error.

Steps To Reproduce:

I have tried to remove as much cruft as possible and get you the general idea:

class Post extends CrossDatabaseModel
{
    protected $connection = 'mysql';
    protected $table = 'posts';

    /**
     * Get the thread which the post belongs to.
     */
    public function thread()
    {
        return $this->belongsTo(Thread::class);
    }
}
class Thread extends CrossDatabaseModel
{
    protected $connection = 'mysql';
    protected $table = 'threads';

    protected static function boot()
    {
        parent::boot();
        static::addGlobalScope(function ($builder) {
            $builder->whereHas('category', function ($query) {
                $query->whereNull('deleted_at');
            });
        });
    }

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}
$messages = Post::whereHas('thread', function($query) use ($category_id) {
    $query->where('category_id', $category_id);
})
->get();