Reputation: 1149
I have a "many to many" relationship
category belongstomany jobs
and
job belongstomany categories
I have two resources: CategoryResources
and JobResources
They are like this:
CategoryResources
'name' => $this->name,
'slug' => $this->slug,
'icon' => $this->icon,
'created_at' => $this->created_at->diffForHumans(),
'jobs' => JobResources::collection($this->jobs)
JobResources
'id' => $this->id,
'title' => $this->title,
'slug' => $this->slug,
'description' => $this->description,
'type' => new TypeResources($this->type),
'categories' => CategoryResources::collection($this->categories)
'created_at' => $this->created_at->diffForHumans()
The problem is that it's taking infinite time to fetch the data. How could I prevent this?
As an alternative I made different resources like JobReverseResource
, but its wrong.
Thanks
Upvotes: 0
Views: 68
Reputation: 396
The reason could be they are calling each other continuously, as a result, it's getting infinite to get data. Or another reason could be you are trying to fetch data before they are ready for you. You can give a try to following code:
// eager loading categories
'categories' => CategoryResources::collection(Category::with('jobs')->get())
// or in case you want them after fetching all data
$category->load('jobs');
// eager loading jobs
'jobs' => JobResources::collection(Job::with('categories')->get())
// or in case you want them after fetching all data
$jobs->load('categories');
Upvotes: 2