CakePHP - paginate和sort hasMany关联

时间:2016-01-10 12:17:32

标签: sorting cakephp paginator

我有三张桌子:

预订 - > belongsTo - >文档,文档 - > hasOne - >书,文件 - > hasMany - >语言,语言 - > belongsTo - >文献

Document.php

public $hasOne = array(
    'Book' => array(
        'className' => 'Book',
        'foreignKey' => 'document_id',
        'dependent'=>true,
    )

public $hasMany = array(
    'Language' => array(
        'className' => 'Language',
        'foreignKey' => 'document_id'
    )

book.php中

public $belongsTo = array(
    'Document' => array(
        'className' => 'Document',
        'foreignKey' => 'document_id'
    )
);

Language.php

public $belongsTo = array(
    'Document' => array(
        'className' => 'Document',
        'foreignKey' => 'document_id'
    )
);

BooksController.php

    $this->Book->bindModel(array(
        'hasOne' => array(
            'Language' => array(
                'foreignKey' => false,
                'conditions' => array('Document.id = Language.document_id')
    ));

    $this->Prg->commonProcess();
    $this->Paginator->settings = [
        'conditions' => $this->Book->parseCriteria($this->Prg->parsedParams()),
        'contain' => array('Document','Language')
    ];
    $this->set('books', $this->Paginator->paginate());

的index.php

            <th><?php echo $this->Paginator->sort('Document.Language.type',__('language')); ?></th>

我无法按语言类型对数据进行排序!

有人可以建议修复此问题吗?

1 个答案:

答案 0 :(得分:1)

您可以使用虚拟字段功能按语言类型排序。

首先,将此虚拟字段添加到Document模型中:

public $virtualFields = ['Min_LangType' => 'SELECT MIN(type) FROM languages as Language WHERE Language.document_id = Document.id'];

然后,按这种方式按语言类型排序:

$this->Paginator->sort('Document.Min_LangType',__('language'));