问题
I have two tables colleges and college_admins. Each College is owned by a CollegeAdmin who is a User. I'm using the Auth component to authorize access to which pages can be viewed by which user.
Now, I want to each CollegeAdmin to list only Colleges owned by him / her.
This is what I'm doing in the CollegesController:
public function index()
{
$this->set('colleges', $this->paginate($this->Colleges->ownedBy($this->Auth->user('id'))));
$this->set('_serialize', ['colleges']);
}
And this is the code I'm using in the CollegesTable:
public function ownedBy($userId)
{
$college_admins = TableRegistry::get('CollegeAdmins');
return $college_admins->find()
->select($college_admins->Colleges)
->leftJoinWith('Colleges')
->where(['CollegeAdmins.user_id' => $userId]);
}
But it's not working. It's showing the number of rows / records correctly, but the fields are being displayed as blank. How to fix this?
回答1:
I found the solution to the problem. I was doing it the wrong way round in the Colleges table. This code works perfectly:
public function ownedBy($userId)
{
return $this->find()
->leftJoinWith('CollegeAdmins')
->where(['CollegeAdmins.user_id' => $userId]);
}
来源:https://stackoverflow.com/questions/35321261/cakephp-3-display-colleges-owned-by-admins