CakePHP3自定义查找器方法使用包含,并在尝试显示关联的模型字段时不起作用

时间:2015-01-17 16:34:46

标签: php orm cakephp-3.0

这是我在DynamicViewsTable.php

中的自定义finder方法
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'

并且错误页面中显示的查询是:

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

1 个答案:

答案 0 :(得分:5)

虽然您可以使用contain()添加任何类型的关联,但匹配某些内容仅适用于1:1n:1关联,即hasOnebelongsTo ,因为这些是contain()将加入相关表格的唯一关联。

出于所有其他目的,您必须使用 matching() (需要最近的开发快照才能与contain()结合使用,特别是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 相关表格:

$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']);

或从另一张表中查询。

另见