问题
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;
}
The error I keep getting is:
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 hasMany UsersAccessDynamicViews
回答1:
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.
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']);
or query from the other table.
See also
- 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
来源:https://stackoverflow.com/questions/28001673/cakephp3-custom-finder-method-using-contain-and-does-not-work-when-attempt-to-di