Building a forum in CakePHP

I have 2 tables, Forumcategories and Forums…they both belong to multiple projects. I am loading a project and trying to contain all the forum categories. I have projects_forumcategories in my database and a has many. Do I also need a Belongstomany association and how would I write a query somewhere along the lines of “$forumcategories= $project->Forumcategories” or "$forumcategories = $this->Forumcategories->where(“contains->project_id”)?

So I have 5 Forumcategories that belong to multiple projects, and ditto setup with forums, I simply want to get only the forumcategories and forums that are decended from ONE project. I have done this with my Tasks model, but one task can only have one project. how would I do this to check if it has multiple projects. I don’t even know how to really phrase my question well, help would be appreciated! This is what I have so far:

public function view($id = null)
{
$this->loadModel(‘Tasks’);
$this->loadModel(‘Forumcategories’);
$this->loadModel(‘Forums’);
$paginate = [‘Tasks’ => [‘conditions’ => [‘project_id’ => $id]]];

    $project = $this->Projects->get($id, [
        'contain' => ['Users', 'Tasks' => ['Users'], 'Forumcategories' => ['Forums'], 'Events', 'Files']
    ]);
	$tasks = $this->Tasks->find('all')->where(['project_id' => $id])->contain(['Users']);
	$forumcategories = $this->Forumcategories->find('all');
	$files = $this->paginate($project->Files, ['scope' => 'file']);
	$this->set('project', $project);
	$this->set('forumcategories', $forumcategories);
	$this->set('tasks', $this->Paginate($tasks));
}

I’m making some assumptions here, but if your models are set up correctly, you should be able to change your Projects query slightly and get everything at once:

$project = $this->Projects->get($id, [
    'contain' => ['Users', 'Tasks' => ['Users'], 'Forumcategories', 'Forums', 'Events', 'Files']
]);

If you debug $project, you should see Forumcategories and Forums separately, and they should include only those entities that are connect to the Project in question.

Per CakePHP documentation, I suggest you rename your projects_forumcategories table to be forumcategories_projects instead (the names should be ordered alphabetically):

https://book.cakephp.org/3.0/en/intro/conventions.html#database-conventions

You noted that the relationships involved are belongsTo and hasMany, but it sounds like you might need to change these to be belongsToMany instead (as you suggested). Forumcategories and Forums both belong to many Projects.

The following page is really helpful for understanding the belongsToMany relationship:

https://book.cakephp.org/3.0/en/orm/associations.html#belongstomany-associations

I hope this helps!