问题描述
这是我在DynamicViewsTable.php中的自定义查找器方法
This is my custom finder method inside DynamicViewsTable.php
public function findAccessibleByUser(Query $query, array $options)
{
if (empty($options['User']['id'])) {
throw new Exception("Current User not set", 1);
}
$query->select(['DynamicViews.id', 'DynamicViews.title', 'UsersAccessDynamicViews.ordinal_ranking'])
->contain(['UsersAccessDynamicViews'])
->where([
'UsersAccessDynamicViews.user_id' => $options['User']['id'],
])
->order(['UsersAccessDynamicViews.ordinal_ranking' => 'ASC']);
return $query;
}
我一直收到的错误是:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'UsersAccessDynamicViews.ordinal_ranking' in 'field list'
,错误页面中显示的查询为:
and the query shown in the error page is:
SELECT DynamicViews.id AS `DynamicViews__id`, DynamicViews.title AS `DynamicViews__title`, UsersAccessDynamicViews.ordinal_ranking AS `UsersAccessDynamicViews__ordinal_ranking` FROM dynamic_views DynamicViews WHERE UsersAccessDynamicViews.user_id = :c0 ORDER BY UsersAccessDynamicViews.ordinal_ranking ASC
DynamicViews有许多UsersAccessDynamicViews
DynamicViews hasMany UsersAccessDynamicViews
推荐答案
尽管可以使用contain()
包括任何类型的关联,但是匹配某些内容仅对1:1
和n:1
关联有效,即hasOne
和belongsTo
,因为这是contain()
将在相关表中加入的唯一关联.
While you can include any type of associaition using contain()
, matching something does only work for 1:1
and n:1
associations, that is hasOne
and belongsTo
, as these are the only associations where contain()
will join in the related tables.
出于所有其他目的,您将必须使用 matching()
(需要一个最新的开发者快照才能与contain()
结合使用,尤其是 更复杂的组合 )
For all other purposes you will have to use either matching()
(requires a recent dev snapshot in order to work when combined with contain()
, escpecially for more complex combinations)
$query
->select(['DynamicViews.id', 'DynamicViews.title', 'UsersAccessDynamicViews.ordinal_ranking'])
->contain(['UsersAccessDynamicViews'])
->matching('UsersAccessDynamicViews', function ($q) use ($options) {
return $q->where([
'UsersAccessDynamicViews.user_id' => $options['User']['id']
]);
})
->order(['UsersAccessDynamicViews.ordinal_ranking' => 'ASC']);
加入 手动相关表:
join in the related tables manually:
$query
->select(['DynamicViews.id', 'DynamicViews.title', 'UsersAccessDynamicViews.ordinal_ranking'])
->contain(['UsersAccessDynamicViews'])
->innerJoin('UsersAccessDynamicViews', [
'UsersAccessDynamicViews.dynamic_view_id = DynamicViews.id',
'UsersAccessDynamicViews.user_id' => $options['User']['id']
])
->order(['UsersAccessDynamicViews.ordinal_ranking' => 'ASC']);
或从其他表中查询.
另请参见
- http://book.cakephp.org/3.0/en/orm/retrieving-data-and-resultsets.html#filtering-by-associated-data
- http://book.cakephp .org/3.0/en/orm/query-builder.html#adding-joins
这篇关于当尝试显示关联的模型字段时,使用包含的CakePHP3自定义查找器方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!