amir5's avatar
Level 7

how to get sub category relation items

I have a categories table with nested categories(parent_id), and in an api endpoint when user gives me a category id I should show them sub root category names of that category with files of each category, but it should also contain files of inner child categories of that category.

0 likes
5 replies
amir5's avatar
Level 7

@tykus How to limit file count? I have a search scope that works fine, but limit doesn't work(returns more than the limit):

$categoryQuery->with('decendantFiles', function (MorphToManyOfDescendants $q) use ($request) {
$q->limit(10)->search(request('q'));
});

and in category model:

    public function decendantFiles(): MorphToManyOfDescendants
    {
        return $this->morphedByManyOfDescendants(File::class, 'categoriable', 'category_item');
    }
amir5's avatar
Level 7

@tykus Query:

limited by 1

Mega_Aleksandar's avatar

Maybe try with a plain parent/child function on the model - belongsTo and hasMany. It should return you all the subcategories ($parent_id == $given_category) and the $given_category itself.

kwakuoseikwakye's avatar

Create a relationship using hasMany() to handle parent and child relationships and add a relationship for files using hasMany(). You should have something like this.

Then in your controller you should eager load and have something like this


class CategoryController extends Controller
{
    public function index($categoryId)
    {
       $category = Category::with(['files', 'allChildren.files'])
            ->findOrFail($categoryId);

        return new CategoryResource($category);
    }

and in your resource you should have something like this


  public function toArray($request)
    {
       return [
            'id' => $this->id,
            'name' => $this->name,
            'files' => $this->whenLoaded('files'),
            'sub_categories' => self::collection($this->whenLoaded('allChildren')),
      ];
   } 

1 like

Please or to participate in this conversation.