I have a category table and a pivot table which determines the child categories. I wanted to use eloquent to select all the top level categories (categories that do not have a parent). I did want to do it with one eloquent query but haven't managed to get my head around it.
Database Structure
library_categories
id
title
slug
library_category_relationships
id
parent_id
category_id
Model
class LibraryCategory extends \Eloquent {
public function children()
{
return $this->belongsToMany('LibraryCategory', 'library_category_relationships', 'parent_id', 'category_id');
}
public function parents()
{
return $this->belongsToMany('LibraryCategory', 'library_category_relationships', 'category_id', 'parent_id');
}
}
Current Query (Located in a repository method)
$relationshipIds = DB::table('library_category_relationships')
->select('category_id')
->distinct()
->get();
// Merge with id of 0 to avoid error in the next query if no relationships are found
$relationshipIds = array_merge([0], array_fetch($relationshipIds, 'category_id'));
return $this->model
->with($this->relationships)
->orderBy($orderBy, $sort)
->whereNotIn('id', $relationshipIds)
->paginate(Config::get('intranet.pagination.per_page'));
As you can see in the first half I fetch all the unique category ids from the pivot table that are children and in the second query I fetch the categories from that are not in the previous results.
Is it possible to some how include this in just one query? I would like to keep this contained within eloquent.
Thanks