Cakephp 不加载两个模型之间的 belongsToMany 关联

Cakephp not loading belongsToMany association beetween two Models

我刚开始用 cakephp3.0 开始我的项目。我从用户开始。我在 UsersController 中放置了一个函数 isAuthorized,它应该验证用户是否被允许查看其他用户、编辑其他用户等等。

我创建了一个 table "userprivileges",其中列出了可以分配给用户的所有可能权限。 table 是 "userprivileges" 是:

id | controller | function

接下来我想将权限分组到角色中。 我创建了以下 table:"userprivilegeroles"

id | role 

接下来我创建了 BTM-Table:"userprivileges_userprivilegeroles"

id | userprivilegerole_id | userprivilegerole_id

用户已链接到 userprivilegeroles table,因此我需要搜索请求的 controller/function 是否可供用户查看。

我这样试过:

$this->loadModel('Userprivilegeroles');
$userprivilegeroles = $this->Userprivilegeroles->find('all', [
    'conditions' => [
        'Userprivileges.controller' => $this->request->controller,
        'Userprivileges.function' => $this->request->action], 
    'contain' => ['Userprivileges']
]);

现在失败并出现以下错误:

Userprivilegeroles is not associated with Userprivileges.

描述有点多,我可以搜索到500页提示的问题

  • The class for the specified table does not exist.
  • The Table was created with a typo: TableRegistry::get('Atricles');
  • The class file has a typo in the name or incorrect namespace: class Atricles extends Table
  • The file containing the class has a typo or incorrect casing: Atricles.php
  • The Table was used using associations but the association has a typo: $this->belongsTo('Atricles')
  • The table class resides in a Plugin but no plugin notation was used in the association definition.

让我们一一道来:

The class for the specified table does not exist.

确实如此:

namespace App\Model\Table;

use Cake\ORM\Table;
use Cake\Validation\Validator;

class UserprivilegerolesTable extends Table
{
    public function initialize(array $config){
        $this->belongsToMany('Userprivileges', [
            'joinTable' => 'userprivileges_userprivilegeroles',
            'className' => 'Userprivileges'
        ]);
    }       
}

下一个

The Table was created with a typo: TableRegistry::get('Atricles');

没有

The class file has a typo in the name or incorrect namespace: class Atricles extends Table

没有

The file containing the class has a typo or incorrect casing: Atricles.php

没有。它在 src/Model/Table/Userprivilegeroles.php

The Table was used using associations but the association has a typo: $this->belongsTo('Atricles')

见上文。我没有看到打字错误。

The table class resides in a Plugin but no plugin notation was used in the association definition.

如上所述,我从 UsersController 调用它。

任何人都可以帮助我找到,为什么关联没有按预期工作?也许我被困在蛋糕 php 2.0 ORM 中,但我几乎可以肯定我按照食谱中描述的那样进行了关联。

我已经搜索并发现了 belongstomany 关联的一些其他问题。但他们都处理保存数据的问题。我想搜索资料,所以我没有看到那里有联系。

实际上文件名 不正确,文件名必须与类名匹配 (PSR-4),所以它应该是 UserprivilegerolesTable.php。警告说明可能需要一些修复或进一步解释,因为它们不使用 Table 后缀有点误导。

一旦你解决了下一个问题,包含 belongsToManyhasMany 关联不能在条件中使用,因为它们是在单独的查询中检索的,你'将不得不使用 matching() 代替。