cakephp-3.0 - 在关联定义中匹配的自定义查找器?

标签 cakephp-3.0

我有两个模型:具有 belongsToMany 关联的联系人和群组。

我只想获取联系人可访问的内容。为此,我有一个自定义查找器。

public function findAccessible(Query $query, array $options){
    return $query
            ->where(['admin_user_id' => $options['User.id']])
            ->orWhere(['public' => true])
            ->matching('Users', function($q) use ($options){
                return $q->orWhere(['Users.id' => $options['User.id']]);
            });
}

这样我就可以调用 following,我会得到我想要的。

$accessibleGroups = $this->Contacts->Groups->find('accessible', ['User.id' => $this->Auth->user('id')]);

但如果我有一个容器,它会返回所有组,而不仅仅是可访问的组。

$contact = $this->Contacts->get($id, [
        'contain' => ['Groups']
    ]);

如何限制可访问的内容?

我无法将自定义查找器添加到表关联定义的查找器属性中,因为我无法在那里传递 $options。或者我可以吗?

最佳答案

让我引用文档和测试(如果您无法在文档中找到某些内容,测试通常是获取有关如何做事的信息的有用来源)。

http://book.cakephp.org/3.0/en/orm/table-objects.html#passing-conditions-to-contain

If you have defined some custom finder methods in your associated table, you can use them inside contain:

// Bring all articles, but only bring the comments that are approved and
// popular.
$query = $articles->find()->contain([
    'Comments' => function ($q) {
       return $q->find('approved')->find('popular');
    }
]);

在那种情况下,您可以简单地在 find() 调用中传递条件,就像您已经在做的那样。


http://book.cakephp.org/3.0/en/orm/table-objects.html#using-the-finder-option

https://github.com/cakephp/cakephp/blob/7fc4cfe3ae7d4c523331a44e2862bab5c8f44f1e/tests/TestCase/ORM/QueryTest.php#L2175

所以还有这个“隐藏的”finder 选项可以用来代替可调用对象:

$table->find('all')
    ->where(['Articles.author_id' => $authorId])
    ->contain([
        'Authors' => [
            'finder' => ['byAuthor' => ['author_id' => $authorId]]
        ]
    ]);

我想如果在 Cookbook 中更详细地记录 finder 的使用也不会有什么坏处,Query::contain() 的文档 block 也缺少有关它的信息。

关于cakephp-3.0 - 在关联定义中匹配的自定义查找器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26926945/

相关文章:

mysql - UTF8 数据库文本无法在 cakephp3 上运行

php - 与同一模型 : from CakePHP 2. x 到 CakePHP 3.x 的多重关系

php - 在 cakephp 3 中创建适当的关联

php - Cakephp 3 输入自动标签

mysql - cakephp3.0 分页给出连接表错误

php - MySQL:向当前用户显示帖子提要和帖子喜欢

mysql - 在 CakePHP 3.x 中,我如何计算 MySql 表中的行数?

php - 在这种特殊情况下,什么原因导致 "Headers already sent"?

php - 具有多个搜索过滤器的 Cake PHP3 分页

session - cakephp 3 如何增加 session 超时