Hi
So I am building a small scale ecommerce application where I want to eager load the parent category if it exists.
I am already eager loading metadata as this is needed everywhere where I use the category and I am using the $with protected field on the model for that.
However, I am facing an issue when I try to do this with a category that is a root category, which means that it has no parent.
protected $with = ['metadata', 'parent'];
public function parent()
{
return $this->belongsTo(Category::class, 'parent_id');
}
public function children()
{
return $this->hasMany(Category::class, 'parent_id');
}
Everything works fine, when all categories either have a parent og no parent at all. As soon as I mix them, the request takes some time to run, even with only two or three categories created. Once the request fails, php artisan servehas cancelled it self.
I have checked storage/logs/laravel.log and nothing is there.
Is there a way for me to always eager load the parent category, but have the relationship return null, like a OneToMany relationship?