custom finder with matching in association definition?
我有两个模型:Contacts 和 Groups with belongsToMany 关联。
我只想获取联系人可以访问的组。为此,我有一个自定义查找器。
1 2 3 4 5 6 7 8 | 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']]); }); } |
所以我可以打电话给关注,我会得到我想要的。
1 | $accessibleGroups = $this->Contacts->Groups->find('accessible', ['User.id' => $this->Auth->user('id')]); |
但是如果我有一个容器,那么它将返回所有组,而不仅仅是可访问的组。
1 2 3 | $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:
1
2
3
4
5
6
7 // 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');
}
]);
在那种情况下,您可以简单地在
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
所以也有这个"hidden"
1 2 3 4 5 6 7 | $table->find('all') ->where(['Articles.author_id' => $authorId]) ->contain([ 'Authors' => [ 'finder' => ['byAuthor' => ['author_id' => $authorId]] ] ]); |
我想如果在 Cookbook 中更详细地记录 finder 的使用不会有什么坏处,