I think your category relationship of the Pages model is wrong, it should be :
public function category()
{
return $this->belongsTo('App\Category', 'category_fk');
}
And your has many relationship names should be pluralized. $maintable->categories and $category->pages.
Finally no need to join anything, just use the relations.
$maintable = Maintable::with('categories.pages')->get();
foreach ($maintable->categories as $category)
{
foreach ($category->pages as $page)
{
// $maintable->id, $category->id, $page->id
}
}
