编辑:我的问题可能过于复杂,让我们简化一下。如何从不同的控制器和表导入/调用表。例如。我如何从ProjectsController调用UsersTable?
如果我想访问和处理使用复合键将两个不同的表绑在一起的表的数据,我应该怎么做?
作为一个例子,我有一个项目和用户以及一个名为ProjectsUsers的表,它跟踪两者的关系(哪些用户被分配到哪个项目及其在该项目中的角色)。使用复合键我可以轻松地烘焙脚手架代码以进行添加和编辑,让我在创建项目时将用户分配给项目,但是这不能让我访问表格中的角色变量。
我在想我应该为ProjectsUsers创建一个模型(我确实使用了bake),然后在ProjectsUsersTable中创建函数来检查给定用户是否具有对他们试图访问的任何内容的访问权限。
ProjectsTable方法isOwnedBy(下面)工作正常,所以我尝试复制它为我的复合表,但没有运气。
ProjectsController:
use App\Controller\AppController;
use App\Model\Table\ProjectsUsers;
class ProjectsController extends AppController
{
//Individual access rules to projects functions (projects/*).
public function isAuthorized($user)
{
// All registered users can add projects.
if ($this->request->action === 'add'){
return true;
}
// Check from the ProjectsUsers table if the person trying to access
// is a moderator of that project.
if ($this->request->action === 'edit'){
$projectId = (int)$this->request->params['pass'][0];
if ($this->ProjectsUsers->isModeratedBy($projectId, $user['id']))
{ return true;
}
}
// The owner of an article can edit and delete it.
if (in_array($this->request->action, ['edit', 'delete'])){
$projectId = (int)$this->request->params['pass'][0];
if ($this->Projects->isOwnedBy($projectId, $user['id'])){
return true;
}
}
return parent::isAuthorized($user);
}
}
ProjectsTable(正常工作):
class ProjectsTable extends Table
{
public function isOwnedBy($projectId, $userId)
{
return $this->exists(['id' => $projectId, 'user_id' => $userId]);
}
}
ProjectsUsersTable:
class ProjectsUsersTable extends Table
{
public function isModeratedBy($projectId, $userId)
{
return true;
}
}
但是我收到了一个错误:
在布尔值
上调用成员函数isModeratedBy()
编辑:我的问题可能过于复杂,让我们简化一下。如何从不同的控制器和表导入/调用表。例如。我如何从ProjectsController调用UsersTable?
答案 0 :(得分:0)
我以为我已经尝试了这一点,所以我感到困惑了一段时间,但正确的做法是:
use Cake\ORM\TableRegistry;
$articles = TableRegistry::get('Articles');
答案 1 :(得分:0)
您应该考虑在模型中使用CakePHP关联:
ProjectsTable:
class ProjectsTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Users', [
'through' => 'ProjectUsers',
]);
}
...
}
UsersTable:
class UsersTable extends Table
{
public function initialize(array $config)
{
$this->belongsToMany('Projects', [
'through' => 'ProjectUsers',
]);
}
...
}
ProjectsUsersTable:
class ProjectsUsersTable extends Table
{
public function initialize(array $config)
{
$this->belongsTo('Projects');
$this->belongsTo('Users');
}
....
}
如果您遵循CakePHP关联,则可以使用可包含行为进行查询。如果您正在使用ProjectsController:
//Find all projects and it's related users.
$projects = $this->Projects->find('all')->contain(['Users']);
//Find all users and it's related projects.
$this->loadModel('Users');
$users = $this->Users->find('all')->contain(['Projects']);
//Find certain user and it's related projects.
$this->loadModel('Users');
$user = $this->Users->find('all')->contain(['Projects'])->where(['Users.id' => 1]);
//After this you can access the projects assigned to this user through $user->projects
注意:还有其他方法可以解决这个问题,但这就是我的方法。